您可以使用类似的东西,但要非常小心。它实际上会导致严重的可追溯错误(例如,当您忘记在 Single 方法中显式设置视图名称时)。
public ActionResult Single(PostModel model) {
// it is important to explicitly define which view we should use
return View("Single", model);
}
public ActionResult Create(PostModel model) {
// .. save to database ..
return Single(model);
}
更清洁的解决方案是像从标准表单发布一样做同样的事情 - 重定向(XMLHttpRequest 将跟随它)
为了返回包装在 json 中的 ajax 视图,我使用以下类
public class AjaxViewResult : ViewResult
{
public AjaxViewResult()
{
}
public override void ExecuteResult(ControllerContext context)
{
if (!context.HttpContext.Request.IsAjaxRequest())
{
base.ExecuteResult(context);
return;
}
var response = context.HttpContext.Response;
response.ContentType = "application/json";
using (var writer = new StringWriter())
{
var oldWriter = response.Output;
response.Output = writer;
try
{
base.ExecuteResult(context);
}
finally
{
response.Output = oldWriter;
}
JavaScriptSerializer serializer = new JavaScriptSerializer();
response.Write(serializer.Serialize(new
{
action = "replace",
html = writer.ToString()
}));
}
}
}
这可能不是最好的解决方案,但效果很好。请注意,您需要手动设置 View、ViewData.Model、ViewData、MasterName 和 TempData 属性。