For now, I just want to use HTTP POST to send json to asp.net mvc2 controller.
Since the JSON is actually a list of JSON objects, and each of them has different fields & length, so it hard for me to make up a input model.
So I want to know is there a way for me to post JSON without model/ajax to a controller in ASP.NET MVC2?
Building on @Brian's answer, we have done exactly this. Keep in mind this is Jquery 1.4.2
This is broken out a bit and could be simplified, but it is using callbacks instead of full on posts. It was initially used for filtering results real time and reloading the first page of them back into the same area.
First, we have the button/link/whatever on the page. This is going to call out javascript to build the json data.
<input type="button" alt="Update" onclick="doStuff();" />
Then, we have the doStuff() function. In this case, refinements is a collection of json objects.
function doStuff() {
var refinements = GetRefinementSelections();
var profileId = '<%= Model.Profile.ProfileId %>';
var startDate = $('#SearchbyDateFrom').val();
var endDate = $('#SearchbyDateTo').val();
var jsonData = JSON.stringify(
{
"ProfileId" : profileId,
"RefinementGroups": refinements,
"StartDate": startDate,
"EndDate": endDate
});
$('#jsonData').val(jsonData);
$('#update-button').click();
}
Next, we have an ajax form with a hidden field inside that doStuff() puts our data into. This could be a regular old form as well.
<% using (Ajax.BeginForm("MyAction", "MyController", new { },
new AjaxOptions { },
new { id = "filteredResultsForm" }))
{ %>
<input type="submit" id="update-button" style="display:none;" />
<%= Html.Hidden("jsonData")%>
<% } %>
So, the click is called on this button, which causes the callback to the server. Here's our action in the controller. JsonSerializer is part of Newtonsoft.Json
public ActionResult MyAction(string jsonData)
{
JsonSerializer serializer = new JsonSerializer();
StringReader sr = new StringReader(jsonData);
Newtonsoft.Json.JsonTextReader reader = new JsonTextReader(sr);
JsonRequest jsonRequest = (JsonRequest)serializer.Deserialize(reader, typeof(JsonRequest));
//do work with object
return View();
}
JsonRequest needs to be a class object, and all properties, sub classes and their properties, and so on and so forth need to be serializable for this approach to work. Despite having a fluid set of data being returned (as a collection of json objects), and without actually seeing what that data looks like, I am fairly certain you could devise some sort of class structure to support your data.
You could store JSON in a Hidden Field, and then convert the JSON to an object in the controller using a utility. It has to be within the form's posted data in order for it to be available; storing in a hidden field is one approach, or use AJAX to stream it back.
HTH.