I was using some old example for MVC2, that used a [fromJson] attribute when posting json to a controller action, it worked fine except that it did not catch model errors, so ModelState.IsValid is always true. Then I saw that posting JSON was build into MVC3 so I have upgraded my code. But now I have another issue :) using:
ko.utils.postJson(location.href, json);
The binding is not working, and my model is empty.
But if I use JQuery:
$.ajax({
url: '@Url.Action("Create")',
contentType: 'application/json; charset=utf-8',
type: "POST",
data: json,
dataType: 'json',
success: function(result) {
alert("yay");
},
error: function(xhr, ajaxOptions, thrownError) {
alert(xhr.statusText + " " + xhr.responseText);
}
});
So I think i will move my ko.utils.postJson to JQuery $.ajax but how do I just post so I can do a RedirectToAction afterwards?
So to clarify! the controller action looks like this:
public ActionResult Create(QuestionViewModel questionViewModel){
if (ModelState.IsValid)
{
questionViewModel.Save();
TempData.Add(Config.MODEL, questionViewModel);
return RedirectToAction("Edit");
}
PopulateViewBag();
return View(questionViewModel);
}
I have found this http://groups.google.com/group/knockoutjs/browse_thread/thread/e631a544de2ad51e in the Knockout forum so ko.utils.postJson is a "normal" form submit. which is what I want to do, so the flow of the application is kept unchanged.