I'm trying to POST a JSON object (a JSON-ified knockout model, if that's of any relevance) to my MVC controller, and have the controller return a new view. To do this, I'm sending the data with a form. The problem is that I would like to have the JSON automatically converted to a model when the controller receives it.
If I were to use an AJAX call for this,
var actionModel = new Object();
actionModel.Controls = ko.toJS(self.controls());
var json = JSON.stringify(actionModel);
$.ajax({
url: "MyController/Preview",
type: "POST",
contentType: 'application/json; charset=utf-8',
cache: false,
data: json,
success: function (data) {
}
});
...the JSON object is successfully deserialized and converted into an instance of my model class.
public ActionResult Preview(ActionModel actionModel) { ... }
public class ActionModel
{
public List<ControlModel> Controls { get; set; }
}
If I want to do this with a form, I understand that I need to insert the JSON into a hidden input field, but the best I can manage when doing this is to receive the data as a serialized string:
@using (Html.BeginForm("Preview", "MyController", FormMethod.Post, new { id = "previewForm" }))
{
<input type="hidden" id="hiddenFieldName" />
}
public ActionResult Preview(string hiddenFieldName) { ... }
I could just deserialize it afterwards, but I really would prefer it if MVC could convert it for me, as it would with an AJAX call. Is this possible?
Thanks.