How do I submit a form via Ajax in ASP.NET MVC?
I have a View made up of several partial views, one of which displays user information with an Edit
button.
When the Edit
button is clicked, I make an ajax call to another Action
that returns a Partial View
which is loaded into a JQuery-UI modal d开发者_JAVA百科ialog.
How do I submit this edit form via Ajax and update the UserInfo
partial view on the main page?
Ajax Call
$('#submitIt').submit(function() {
var createdBy = $('#createdBy').val();
$.ajax({
type: "POST",
url: '/MyController/GetContact/',
dataType: "html",
data: { 'createdBy': createdBy },
success: function (result) {
$('#myLittleForm').html(result);
},
error: function (request, status, error) {
//Do Something on Failure
}
});
});
Controller
[HttpPost]
public ActionResult GetContact(string createdBy)
{
ViewData["CreatedBy"] = createdBy;
return PartialView("MyView");
}
Markup
<div id="myLittleForm">
<form action="/MyController/GetContact/" method="post">
<input id="createdBy" type="text"/> <br/>
<input id="submitIt" type="submit" value="Submit"/>
</form>
</div>
Note
When you submit the form under markup, the ajax call is made and the div "myLittleForm" is replaced with your partial view.
Edit: oops, the scripts didn't show - fixing You'll need to reference the Ajax scripts shown here:
<script src="../../Scripts/MicrosoftAjax.js" type="text/javascript"></script>
<script src="../../Scripts/MicrosoftMvcAjax.js" type="text/javascript"></script>
<script src="../../Scripts/AjaxLoadedContentScriptFix.js" type="text/javascript"></script>
I don't recall what that last script is, but I'm using it in my app so it probably can't hurt :)
Then you'll need to use Ajax.BeginForm in your view to post a form asynchronously. It takes an AjaxOptions parameter that will allow you to specify the update target, success callbacks, etc. Example:
<% Ajax.BeginForm("FormName" , new { id = Model.SomeProperty },
new AjaxOptions { UpdateTargetId = "MyDivToUpdate", OnSuccess = "onSuccess" }); %>
精彩评论