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?
I need some clarification on GET and POST concerning JQuery AJAX and MVC 3
Asked Answered
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.
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")
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.
Please never use Knockout MVC. Sending calls to the server for every function is wasteful. –
Fanni
i second that motion re knockoutmvc - don't do it- ever -please, pretty please... –
Grimy
© 2022 - 2024 — McMap. All rights reserved.