摘要:MVC的Ajax實現方式(一)
一、 WEB的Form採取異步方式,Form格式如下:
<div id="addPersonModal" style="display:none;">
<% using (Ajax.BeginForm("JsonAdd", "People", new AjaxOptions { OnComplete = "JsonAdd_OnComplete" }))
{%>
<fieldset>
<legend>Add a Person</legend>
<%= Html.LabelFor(model => model.AddPersonModel.FirstName)%>:
<%= Html.TextBoxFor(model => model.AddPersonModel.FirstName, new { @class = "firstname" })%>
<%= Html.ValidationMessageFor(model => model.AddPersonModel.FirstName)%>
<%= Html.LabelFor(model => model.AddPersonModel.LastName)%>:
<%= Html.TextBoxFor(model => model.AddPersonModel.LastName, new { @class = "lastname" })%>
<%= Html.ValidationMessageFor(model => model.AddPersonModel.LastName)%>
<input id="AddBtn" name="AddBtn" type="submit" value="Add" />
</fieldset>
<% } %>
</div>
註釋:JsonAdd 代表Form對應的Action; People代表Controller , AjaxOption有表單處理的各個可選參數:
Confirm(彈出js中的confirm信息)
HttpMethod (Post or Get)
InsertionMode
LoadingElementDuration
LoadingElementId
OnBegin
OnComplete(異步事件結束後的處理)
OnFailure(異步事件失敗後的處理)
OnSuccess(異步事件成功後的處理)
UpdateTargetId(返回數據並更新i頁面的元素)
Url(發送請求的URL)
ToUnobtrusiveHtmlAttributes方法 (以 HTML 屬性集合形式傳回 Ajax 選項以支援非干擾性的 JavaScript。)
Controller代碼如下:
public JsonResult JsonAdd(AddPersonViewModel AddPersonModel)
{
#region for demo purposes
List<Person> _personList = Session["PersonListDB"] as List<Person>;
#endregion
// do validation
Person newPerson = new Person
{
FirstName = AddPersonModel.FirstName,
LastName = AddPersonModel.LastName
};
// call your Repository to add the new Person
_personList.Add(newPerson);
// return a Json Object, you could define a new class
return Json(new
{
Success = true,
Message = "The person has been added!",
PartialViewHtml = RenderPartialViewToString("PersonList", new PersonListViewModel {PersonList = _personList})
});
}
Partial View 的HTML部分顯示如下:
protected string RenderPartialViewToString(string viewName)
{
return RenderPartialViewToString(viewName, null);
}
protected string RenderPartialViewToString(object model)
{
return RenderPartialViewToString(null, model);
}
protected string RenderPartialViewToString(string viewName, object model)
{
if (string.IsNullOrEmpty(viewName))
viewName = ControllerContext.RouteData.GetRequiredString("action");
ViewData.Model = model;
using (StringWriter sw = new StringWriter())
{
ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
ViewContext viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
viewResult.View.Render(viewContext, sw);
return sw.GetStringBuilder().ToString();
}
}
function JsonAdd_OnComplete(context) {
debugger;
var JsonAdd = context.get_response().get_object();
if (JsonAdd.Success) {
$("#PersonList").html(JsonAdd.PartialViewHtml);
}
$("#message").html(JsonAdd.Message);
}
人生到處知何似
應似飛鴻踏雪泥