I have the following .net class in c#:
public class BusinessModel
{
public string BlobName { get; set; }
public string NewName { get; set; }
}
And I have the following action in my MVC Ajax Controller:
[HttpPost]
public ActionResult DoBusiness(string handle, BusinessModel businessData)
{
// Do stuff with the business data.
}
First I try to use the following Javascript code to invoke this:
var bd = JSON.stringify({ BlobName: "blob", NewName: "new" });
$.ajax({
type: "POST",
url: "/Ajax/DoBusiness",
data: { handle: "MyHandle", businessData: bd },
success: businessComplete,
error: businessFailed
});
And in this case, using fiddler to view, the following is how the data is rendered on the request:
handle=MyHandle&businessData=%7B%22BlobName%22%3A%22blob%22%2C%22NewName%22%3A%22new%22%7D
Which is the following decoded:
handle=MyHandle&businessData={"BlobName":"blob","NewName":"new"}
But when I use the Visual Studio debugger to look at the values actually passed to the controller action, the value of the parameter "handle" is "MyHandle" as expected, but the value of the parameter "businessData" is null.
Now I alter the Javascript code to read as follows (merely removing the JSON.stringify call):
var bd = { BlobName: "blob", NewName: "new" };
$.ajax({
type: "POST",
url: "/Ajax/DoBusiness",
data: { handle: "MyHandle", businessData: bd },
success: businessComplete,
error: businessFailed
});
In this case, the data (shown by fiddler) is rendered in the request as:
handle=MyHandle&businessData%5BBlobName%5D=blob&businessData%5BNewName%5D=new
Which is the following decoded:
handle=MyHandle&businessData[BlobName]=blob&businessData[NewName]=new
And in this case, the Visual Studio debugger still shows that "handle" is set to "MyHandle" as expected, but instead of being null, the "businessData" parameter is filled with an actual instance, but both properties "BlobName" and "NewName" are set to null.
Finally the question: What am I doing wrong? How can I actually get that class properly populated in the controller action?
EDIT In response to comment on possible duplicate: The possible duplicate, titled "Send JSON data via POST (ajax) and receive json response from Controller (MVC)" specifically addresses how to send instances of models bound with MVC binding. My question is more not related to an object that might be MVC-bound. I am curious about how to populate ANY object, that might be arbitrarily provided.
EDIT In response to Stephen's comment: This is a simplified scenario. The real-life actual use-case has an overlapping set of Ajax calls, and this one is called in response to a previous one which has passed along an arbitrary object constructed on the server which it wants back in the subsequent call (this example). Providing that fully-fleshed real-life use case would, in my opinion, make this question unduly long, so pardon the simplification, and I hope this explanation will serve to appropriately frame the context.