I need some clarification on GET and POST concerning JQuery AJAX and MVC 3

好久不见. 提交于 2019-12-23 05:40:13

问题


I am wondering if it is an all-or-nothing situation. What I would like to do, Load (GET) my page by normal MVC 3. Controller takes Model and passes it to View. View and Razor render it. However, when I post back, I'd like it to postback the selected info through AJAX. Is this possible? Or do I have do GET and POST with AJAX?


回答1:


You can certainly POST using AJAX after GETting using other means.

Here's a random question on SO that does just this:

Ajax post in MVC 3 with multiple-form View

The GET and POST actions do not have to be related at all.




回答2:


Try something like the below.
Controller Code:

[HttpGet]
    public ActionResult WhateverActionName()
    {
        YourViewModel yvm = new YourViewModel();
        //Initalize viewmodel here
        Return view(yvm);
    }
[HttpPost]
public ActionResult WhateverActionName(YourViewModel yvm)
{
    if (ModelState.IsValid) {
        RedirectToAction("OtherAction", "OtherController")
    }
    return View(yvm);
}

Ajax:

$.ajax({
    url: myurl
    // processData: false, // you may need this option depending on service setup
    success: function(){
        location.href = "TARGET LOCATION";
    },
    type: "POST"
});

For target location: You're going to need to feed the ajax a variable containing whatever URL the following generates

@URL.Action("Action", "Controller")



回答3:


http://knockoutmvc.com offers an nice way of integrating server side code with client side and it looks like it might help you easily achieve what you want.



来源:https://stackoverflow.com/questions/11617329/i-need-some-clarification-on-get-and-post-concerning-jquery-ajax-and-mvc-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!