我有两个视图(创建/编辑),它们使用EditorTemplate进行用户输入的GET / POST。 EditorTemplate有一个jQuery对话框,用于捕获一些其他信息。
提交表单时,对话框中的元素未发布。因此,它也搞砸了验证。验证将触发并更改元素的css类,但在编辑后不会更改。
当我从对话框中拉出元素时,这些值将绑定到ViewModel,并且验证将按预期工作。
我之前将对话框中的值(使用不同的名称)复制到一些隐藏字段以绑定到ViewModel - 这可以有效但验证隐藏字段而不是具有实际值的字段。
如何将元素绑定到ViewModel并仍然使用jQuery对话框?
代码示例
@* The Create View *@
@using(Html.BeginForm())
{
@Html.ValidationSummary(false, "Please fix these errors:");
@Html.EditorForModel("JobRecord", Model);
<div id="button">
<p>
@Html.Button("Create", new Dictionary<string, object>() { { "id", "create" }, { "type", "submit" } })
@Html.Button("Cancel", new Dictionary<string, object>() { { "id", "cancel" }, { "type", "button" } })
</p>
</div>
}
@* The Edit Template *@
@model GyroviewOpsManager.UI.Models.JobRecordViewModel
@{
Html.Assets().Styles.Add("/Content/jobrecord.css");
Html.Assets().Styles.Add("/Content/themes/base/jquery.ui.all.css");
Html.Assets().Scripts.Add("/Scripts/jobrecord.js");
Html.Assets().Scripts.Add("/Scripts/jquery-ui-1.8.22.min.js");
}
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
<table id="jobinfo-table">
<tr>
<td>
<a id="opener" href="#">Job Number...</a>
</td>
<td>
@Html.TextBoxFor(model => model.JobNo)
</td>
...
</tr>
</table>
@* The div for the jQuery dialog *@
<div id="dialog" title="Job Number Editor">
<p>* All fields are required</p>
<table id="jobnumedit-table">
<tr>
<td>Job Number:</td>
<td>@Html.TextBoxFor(model => model.JobNo, new { id = "jobNo", @readonly = "readonly" })</td>
</tr>
<tr>
<td>Location:</td>
<td>@Html.DropDownListFor(model => model.Location, new SelectList(Model.Locations, "LocnID", "Name", ViewBag.UserLocation), "-- Select --", new{id="Location"})</td>
</tr>
<tr>
@{
var jobNoDate = Model.JobNoDate;
if (Model.JobNoDate == null)
{
jobNoDate = DateTime.Today;
}
}
<td>Date:</td>
<td>@Html.TextBoxFor(model => model.JobNoDate, new{id="JobNoDate"})</td>
</tr>
...
</table>
</div>
<script type="text/javascript">
// Dialog script
$("#dialog").dialog({
autoOpen: false,
height: 450,
width: 450,
modal: true,
buttons: {
"Ok": function () {
...
$(this).dialog("close");
},
"Cancel": function () {
$(this).dialog("close");
}
}
});
$("#opener").click(function () {
...
return false;
});
</script>
答案 0 :(得分:2)
我从另一个关于SO的问题中找到了这个问题的答案。
如果其他人遇到此问题,jQuery-UI对话框不会附加到表单,它会在之前附加,因此要验证的元素位于该部分之外
上面答案的问题标题不是那么明显,所以链接:jQuery UI Dialog validation without using <form> tags
答案包括一个样本。