使用扩展方法RenderToString和basead on cacois answer,你可以像这样创建你的动作:
public ActionResult Edit(SettingViewModel model) { // "Ifs" to return only partials if (ModelState.IsValid) { return PartialView("EditSetting", model); } ... // Returning a Json with status (success, error, etc), message, and the content of // your ajax, in your case will be a PartialView in string return Json(new { Status = 1, Message = "error message", AjaxReturn = PartialView("EditSetting", model).RenderToString()}); }
PS.我建议你创建一个模型来定义Ajax的回报,有Status
,Message
和AjaxReturn
.这样,您的ajax请求将始终返回相同的对象类型.对于该Status
属性,您可以创建一个枚举.
你的ajax请求将是这样的:
$.ajax({ url: this.action, type: this.method, data: $(this).serialize(), success: function (data) { if(data.Message == undefined) { // Use data like a partial } else { // Use data.Message for the message and data.AjaxReturn for the partial } }, error: function (message) { logOut($self, message); } });