假设你有以下表格:
<form id="ajax-form">
<fieldset>
<input type="text" id="firstname" name="firstname" />
<input type="text" id="lastname" name="lastname" />
<input type="submit" value="send" />
</fieldset>
</form>
使用 jQuery
$(document).ready(function(){
$("#ajax-form").submit(function(){
$.ajax({
type: "POST",
url: "Person/Add",
data: $("#ajax-form").serialize(),
success: function (response) {
// whatever you want to happen on success
},
error: function (response) {
alert('There was an error.');
}
});
});
});
在操作方法中访问您的数据。
public ActionResult Add(FormCollection form)
{
string firstname = form["firstname"];
string firstname = form["lastname"];
// do whatever you want here
// then return something to the view
return Json(/*some object*/);
}
另一种方法是使用 Microsoft Ajax
<% using (Ajax.BeginForm("Add", "Person",
new AjaxOptions() {
UpdateTargetId = "formDiv",
InsertionMode = InsertionMode.Replace,
HttpMethod = "Post" })) {%>
<fieldset>
// Form Elements Here.
</fieldset>
<% } %>
UpdateTargetId 是要定位的 html 元素的 id。
InsertionMode 选项有三个值Replace、InsertAfter、InsertBefore
希望对你有帮助
更新:您不必在操作方法中返回 Json 结果,您可以简单地返回部分视图或任何 HTML 代码作为响应对象,然后使用 jQuery 将其插入。