我有两个视图(创建/编辑),它们使用 EditorTemplate 获取/发布用户输入。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>