フォームのAJAX送信を使用する必要があります。続行する方法は次のとおりです。コントローラ
public class MyViewModel
{
public string Foo { get; set; }
[Required(ErrorMessage = "The bar is absolutely required")]
public string Bar { get; set; }
}
:
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult Create()
{
return PartialView("Create");
}
[HttpPost]
public ActionResult Create(MyViewModel model)
{
if (!ModelState.IsValid)
{
return PartialView(model);
}
// TODO: the model is valid => do some processing with it
// and return a JSON result confirming the success
return Json(new { success = true });
}
}
とメインビュー(~/Views/Home/Index.cshtml
):
<script src="@Url.Content("~/Scripts/jquery-ui-1.8.11.js")" type="text/javascript"></script>
<script type="text/javascript">
// Remark: all this javascript could be placed in a separate js file
// to avoid cluttering the views
$(function() {
$('#modalLink').click(function() {
$('#dialog').load(this.href, function() {
$(this).dialog();
bindForm(this);
});
return false;
});
});
function bindForm(dialog) {
$('form', dialog).submit(function() {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (result) {
if (result.success) {
alert('thanks for submitting');
$('#dialog').dialog('close');
} else {
$('#dialog').html(result);
bindForm();
}
}
});
return false;
});
}
</script>
@Html.ActionLink("open modal", "create", null, null, new { id = "modalLink" })
<div id="dialog"></div>
として常に対話形式の情報を表現するビューモデルで始まります部分図(~/Views/Home/Create.cshtml
)は、モーダルで示された形式を含みます。
@model MyViewModel
@using (Html.BeginForm())
{
<div>
@Html.LabelFor(x => x.Foo)
@Html.EditorFor(x => x.Foo)
@Html.ValidationMessageFor(x => x.Foo)
</div>
<div>
@Html.LabelFor(x => x.Bar)
@Html.EditorFor(x => x.Bar)
@Html.ValidationMessageFor(x => x.Bar)
</div>
<input type="submit" value="OK" />
}