I have a form in MVC 3. Currently I am doing the following to post the form. The form is getting posted and it is doing full page refresh to show the result.
After submit the controll will send a status Success or Failure. That's it. I just need to show in a div the success or failure message based on the returned status.
Does anyone know the highlevel steps on how to do this in MVC 3?
<div id="ShowResultHere"></div>
@using (Html.BeginForm("Update", "Test", FormMethod.Post, new { id="frmUpdate"}))
{
//form fields
<button type="submit" class="sprt bg_red bt_red h27">Up开发者_运维知识库date</button>
}
[HttpPost]
public ActionResult Update(TestModel model)
{
return Json(new { s = "Success" });
}
I want the Success to appear silently inside the ShowResultHere div onsuccess callback.
Can this be done in MVC 3?
You could subscribe for the submit
event of the form and perform the AJAX call, like this:
$(function() {
$('#frmUpdate').submit(function() {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function(result) {
// The AJAX call succeeded and the server returned a JSON
// with a property "s" => we can use this property
// and set the html of the target div
$('#ShowResultHere').html(result.s);
}
});
// it is important to return false in order to
// cancel the default submission of the form
// and perform the AJAX call
return false;
});
});
You can also achieve this by not writing any javascript at all. By using an AJAX form
<div id="ShowResultHere"></div>
@using (Ajax.BeginForm("Update", new AjaxOptions { UpdateTargetId = "ShowResultHere" }))
{
}
And in your controller
[HttpPost]
public ActionResult Update(TestModel model)
{
if(blah)
return PartialView("Success")
return PartialView("Failed")
}
Doing it this way means you have to make two views. But means no writing javascript.
look at this example Async operations with jQuery Ajax and Asp.Net MVC
If you are submitting the form through jQuery Ajax, you could display your message client-side in the success callback function.
精彩评论