我按照Darin Dimitrov的例子在模态对话框中提交表格(带有验证):
Using Ajax.BeginForm with ASP.NET MVC 3 Razor
它与异常完美配合。当我提交有意错误的表格时,我最终会在对话框中找到两份表格副本:
以下是我的部分观点:
@model MvcAppTemplate.ViewModels.SupportClass1ViewModel
<script src="~/Scripts/Jquery/jquery.validate.min.js"></script>
<script src="~/Scripts/Jquery/jquery.validate.unobtrusive.js"></script>
<script>
$(document).ready(function () {
$('#SupportClass1Name').focus();
$('form').submit(function () {
if ($(this).valid()) {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (result) {
$('#result').html(result);
}
});
}
return false;
});
});
</script>
<div id="result"></div>
@using (Html.BeginForm("CreateDialog", "SupportClass1", FormMethod.Post, new { @class = "form-horizontal" }))
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true, "The following errors occurred:", new { style = "color: red" })
<fieldset>
<legend>MyMainClass1</legend>
@Html.ValidationMessage("CustomError", new { @class = "error" })
@Html.HiddenFor(model => model.IsNew)
<div class="form-group">
<div class="col-lg-3 control-label">
@Html.LabelFor(model => model.SupportClass1Name)
</div>
<div class="col-lg-6">
@Html.TextBoxFor(model => model.SupportClass1Name, new { style = "width: 400px;", @maxlength = "50" })
@Html.ValidationMessageFor(model => model.SupportClass1Name)
</div>
</div>
<div class="form-group">
<div class="col-lg-3 control-label">
@Html.LabelFor(model => model.Active)
</div>
<div class="col-lg-6">
@Html.EditorFor(model => model.Active, new { style = "width: 150px;" })
@Html.ValidationMessageFor(model => model.Active)
</div>
</div>
<p>
<input type="submit" value="Create" class="btn btn-primary" />
@Html.ActionLink("Cancel", "Search", "SupportClass1", null, new { @class = "btn btn-default" })
</p>
</fieldset>
}
我称之为模态的视图:
@model MvcAppTemplate.ViewModels.SupportClass1ViewModel
@{
ViewBag.Title = "Test";
}
<link href="~/Scripts/jquery-ui-1.11.1.custom/jquery-ui.min.css" rel="stylesheet" />
<link href="~/Content/dataTables.bootstrap.css" rel="stylesheet" />
<script src="~/Scripts/jquery-ui-1.11.1.custom/jquery-ui.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#dialog').dialog({
autoOpen: false,
width: 600,
height: 400,
resizable: true,
title: 'Support Class 1',
modal: true,
open: function (event, ui) {
$(this).load("@Url.Action("CreateDialog", "SupportClass1")");
},
buttons: {
"Close": function () {
$(this).dialog("close");
}
}
});
$("#opener").click(function () {
$("#dialog").dialog("open");
});
});
</script>
<div id="dialog" title="Create" >Please wait</div>
<button id="opener">Show Class</button>
最后我的控制器:
// create in a pop up dialog
public ActionResult CreateDialog()
{
var lvm = new SupportClass1ViewModel
{
IsNew = true,
};
return PartialView("_CreateDialog",lvm);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult CreateDialog(SupportClass1ViewModel lvm)
{
SupportClass1 supportClass1 = new SupportClass1();
// Use Injector to handle mapping between viewmodel and model
supportClass1.InjectFrom(lvm);
try
{
if (ModelState.IsValid)
{
supportClass1Service.CreateSupportClass1(supportClass1);
// redirect to the myMainClass1 view
//return RedirectToAction("Details", "SupportClass1", new { id = supportClass1.SupportClass1Id });
return Content("Thanks", "text/html");
}
}
catch (DataException de)
{
//Log the error (add a variable name after DataException)
var s = de.InnerException.ToString();
ModelState.AddModelError("CustomError", "Unable to save changes. Try again, and if the problem persists, see your system administrator. Error: " + s);
}
// rehydrate the view
lvm.IsNew = true;
//return Content("Thanks", "text/html");
return PartialView("_CreateDialog", lvm);
当出现错误时,部分视图会出现两次加载:一次出现在结果div中,一次出现在原来的@using Html.BeginForm()中。我通过在结果div周围放置一个可见边框来验证这一点。
感谢任何帮助。
答案 0 :(得分:2)
我想出了一个解决办法。正如我在评论中所说,我将部分视图的形式包含在div中:
<div id="myForm">
@using (Html.BeginForm("CreateDialog", "SupportClass1", FormMethod.Post, new { @class = "form-horizontal" }))
{
some content...
}
</div>
然后,在我的jquery表单提交函数中,我清除了div,然后使用部分视图从控制器重新填充它(具有验证错误的那个:
$('form').submit(function () {
if ($(this).valid()) {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (result) {
$('#myForm').html('');
$('#result').html(result);
}
});
}
return false;
});
答案 1 :(得分:0)
这一行是问题所在:
success: function (result) {
$('#result').html(result);
}
在成功和失败方案中都会调用此处理程序,因此您最终会显示两次,一次是原始渲染,然后是错误发生时的结果div。
将您的控制器代码更改为:
try
{
if (ModelState.IsValid)
{
supportClass1Service.CreateSupportClass1(supportClass1);
// redirect to the myMainClass1 view
//return RedirectToAction("Details", "SupportClass1", new { id = supportClass1.SupportClass1Id });
return Json(new {success = true, message ="Thanks" } );
}
}
catch (DataException de)
{
//Log the error (add a variable name after DataException)
var s = de.InnerException.ToString();
ModelState.AddModelError("CustomError", "Unable to save changes. Try again, and if the problem persists, see your system administrator. Error: " + s);
}
return Json(new {success = "false", message = "Error"}); // do a concatenation of the model state errors
然后你的成功处理程序看起来像
success: function (result) {
if(result.success) {
$('#result').html(result.message);
}
else {
// provide some highlighting or what have you or just set the message
$('#result').addClass("error").html(result.message);
}
}