问题
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