I implemented a small test that is based on Scott Guthrie article http://weblogs.asp.net/scottgu/archive/2010/07/27/introducing-asp-net-mvc-3-preview-1.aspx
But my controller action thinks that object passed to it is null, even though I used JSON.stringify
on it and packed data to it - I followed the article exactly.
In my HTML
@using (Html.BeginForm("SomeAction", "ControllerName", FormMethod.Post, new { id = "FormID" })) {
<div class="editor-field">@Html.EditorFor(model => model.Date)</div>
<div class="editor-field">@Html.EditorFor(model => model.Id)</div>
<div class="editor-field">@Html.EditorFor(model => model.Name)</div>
<input type="button" value="save" onclick="Save();" />
}
In my model file
namespace MyNamespace.Models
{
public class MyModel
{
public string Id { get; set; }
public string DateReceived { get; set; }
public string Name { get; set; }
}
}
In my JS
function Save() {
var myModelObj = { Id: $("#Id").val(),
DateReceived: $("#DateReceived").val(),
Name: $("#Name").val()
};
$.ajax({
type: "POST",
url: "/ControllerName/SomeAction",
data: JSON.stringify(myModelObj),
cache: false,
// dataType: "json",
success: function (data) {
alert('success!');
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert('error');
alert(XMLHttpRequest + "<br />" + textStatus + "<br />" + errorThrown);
}
});
In my controller
[HttpPost]
public ActionResult SomeAction(MyModel modelObj )
{
using (StreamWriter sw = new StreamWriter("/test.txt") )
{
sw.Write(modelObj.Id);
}
return null;
}
When I put a break point on sw.Write...statement, modelObj.Id is null.
Am I missing something or is there anything else that needs to be wired up?
I think you need to add the contentType and dataType options to your ajax call.
contentType: 'application/json, charset=utf-8',
dataType: 'json',