您將需要使用AJAX提交表單。以下是如何繼續。
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
):
public class MyViewModel
{
public string Foo { get; set; }
[Required(ErrorMessage = "The bar is absolutely required")]
public string Bar { get; set; }
}
然後控制器:
<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" />
}