このようなものを使用できますが、これには十分注意してください。実際には、追跡可能なエラーが発生する可能性があります(たとえば、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の各プロパティを手動で設定する必要があることに注意してください。