开发者

Knockout and ko.utils.postJson issue

开发者 https://www.devze.com 2023-03-30 22:24 出处:网络
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 alw

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: 开发者_StackOverflowfunction(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.


Since $.ajax() does not create a <form> tag and submit it, you cannot do things like RedirectToAction, during ajax posts. ko.utils.postJson allowed you to do all that because it internally created a quick form tag in the dom and submitted it via script.

What you can do is :

$.ajax({
  statusCode: {
    302: function() {
      window.location.replace("http://Domain.com/Controller/Edit")
    }
  }
});

This question helped me find the way to redirect browser via script. This page tells you how to handle different status codes returned by the server. ASP.NET MVC3 returns 302 status code when you use RedirectToAction() in the Controller. And this can be handled, by adding the approperiate handler as shown above.

0

精彩评论

暂无评论...
验证码 换一张
取 消