我的视图中有一个对话框,其中有一个包含checbox列表的编辑器模板。
想法是,用户进行选择并点击对话框中的选择按钮,向控制器操作方法发出请求,返回更新的模型。
所以发生的事情是它成功地击中了控制器,返回了带有新模型属性值的更新视图,但我相信因为我没有正确刷新DOM,所以新模型值不会反映在页面上。
我应该刷新包含模型属性的div吗?或者.LOAD而不是.Post
$('#main').load('@Url.Action("Create", "RunLogEntry")', { $("#form").serialize() });
var RunDialog;
$(document).ready(function () {
RunDialog = $("#runDatestreeview").dialog({ closeOnEscape: true, stack: false, autoOpen: false, modal: false, resizable: false, draggable: true, title: 'Select Run Dates:', width: 600, height: 500,
buttons: { Select: function () {
$.post("/RunLogEntry/Create",
$("#form").serialize(),
function (data) {
$('main').html(data);
}, "json");
},
Cancel: function () {
$(this).dialog("close");
}
}
});
$('#RunDatesChildDialogLink').click(function () {
RunDialog.dialog('open');
$("#runDatestreeview").parent().appendTo("form");
});
// $("#runDatesList").appendTo("#runDatestreeview");
});
编辑
查看:
@model RunLog.Domain.Entities.RunLogEntry
@{
ViewBag.Title = "Create";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<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>
<script src="@Url.Content("~/Scripts/errorCode.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/runDates.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/testexception.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/runLogEntry.js")" type="text/javascript"></script>
<script type="text/javascript">
var runlogListErrorsUrl = '@Url.Action("ListErrorCodes", "RunLogEntry")';
</script>
<fieldset>
<legend>Enter a new Run Log Entry</legend>
<div id="main">
@using (Html.BeginForm("Create", "RunLogEntry", FormMethod.Post, new { id = "form", enctype = "multipart/form-data" }))
{
@Html.ValidationSummary(true)
<div class="exception">@(ViewBag.ErrorMessage)</div>
<div class="bodyContent">
<span class="leftContent">Load List File (Select): </span><span class="rightContent">
<input type="file" name="file" id="file1" style="width: 500px" />
</span>
</div>
if (Model.LoadListStoredFileName != null)
{
<div class="bodyContent"> <span class="leftContent">Attached Load List: </span><span
class="rightContent">
@Html.ActionLink(Model.LoadListFileName, "Download", new { @file = Model.LoadListStoredFileName })
</span> </div>
}
<div class="bodyContent">
<span class="leftContent">Output File (Select): </span><span class="rightContent">
<input type="file" name="file" id="file2" style="width: 500px" />
</span>
</div>
if (Model.OutputStoredFileName != null)
{
<div class="bodyContent"> <span class="leftContent">Attached Output: </span><span
class="rightContent">
@Html.ActionLink(Model.OutputFileName, "Download", new { @file = Model.OutputStoredFileName })
</span> </div>
}
<div class="bodyContent">
<span class="leftContent">.LOG File(s) -Zip: </span><span class="rightContent">
<input type="file" name="file" id="file3" style="width: 500px" />
</span>
</div>
if (Model.AttachedLogFileName != null)
{
<div class="bodyContent"> <span class="leftContent">Attached Log File(s): </span><span
class="rightContent">
@Html.ActionLink(Model.AttachedLogFileName, "Download", new { @file = Model.AttachedLogFileName })
</span> </div>
}
<div class="bodyContent">
<span class="leftContent">Import Files: </span>
<button name="submit" class="art-button" type="submit" value="Upload" style="width: 100px">
Upload</button>
<button name="submit" class="art-button" type="submit" value="Remove" style="width: 100px">
Remove</button>
</div>
<div class="bodyContent">
<span class="leftContent">
@Html.Label("Operator")
</span><span class="rightContent">
@Html.DropDownList("OperatorID", String.Empty)
</span>
</div>
<div class="bodyContent">
<span class="leftContent">
@Html.Label("Run ID")
</span><span class="rightContent">[Generated] </span>
</div>
<div class="bodyContent">
<span class="leftContent">
@Html.Label("Run Start Date / Time")
</span><span class="rightContent">
@Html.EditorFor(model => model.RunDate)
@Html.DropDownList("Hour", ListHelpers.HourList())
:
@Html.DropDownList("Minute", ListHelpers.Minute15List())
@Html.DropDownList("AMPM", ListHelpers.AMPMList())
</span>
</div>
<div class="bodyContent">
<span class="leftContent">
@Html.Label("System")
</span><span class="rightContent">
@Html.DropDownList("SystemID", String.Empty)
</span>
</div>
<div class="bodyContent">
<span class="leftContent">
@Html.Label("Run Type")
</span><span class="rightContent">
@Html.DropDownList("RunTypeID", String.Empty)
</span>
</div>
<div class="bodyContent">
<span class="leftContent">
@Html.Label("Run Description")
</span><span class="rightContent">
@Html.TextAreaFor(model => model.RunDescription, new { style = "width: 600px; height=30px" })
</span>
</div>
<div class="bodyContent">
<span class="leftContent">
@Html.Label("Assay Performance Issues")
</span><span class="rightContent">
@Html.DropDownList("AssayPerformanceIssues1", ListHelpers.YesNoList())
</span>
</div>
<div class="bodyContent">
<span class="leftContent">
@Html.Label("Tests/Cycles Requested")
</span><span class="rightContent">
@Html.EditorFor(model => model.SPTestsRequested)
</span>
</div>
<div class="bodyContent">
<span class="leftContent">
@Html.Label("Tests/Cycles Completed")
</span><span class="rightContent">
@Html.EditorFor(model => model.SPTestsCompleted)
</span>
</div>
<div class="bodyContent">
<span class="leftContent">
@Html.Label("Run Status")
</span><span class="rightContent">
@Html.DropDownList("RunStatusID", String.Empty)
</span>
</div>
<div class="bodyContent">
<span class="leftContent">
@Html.Label("Assay")
</span><span class="rightContent">
@Html.ListBoxFor(model => model.SelectedAssayIDs, new MultiSelectList(RunLog.Domain.Lists.GlobalList.AssayListItems(), "ID", "Name", Model.SelectedAssayIDs))
</span>
</div>
<div class="bodyContent">
<span class="leftContent">
@Html.Label("Run Dates")
</span><span class="rightContent"><span id="RunDatesChildDialogLink" class="treeViewLink">
Click here to Select Run Dates</span>
<br />
<span id="RunDatesDisplayy" style="cursor: pointer; text-decoration: underline;">
</span></span>
</div>
<div class="bodyContent">
<span class="leftContent">
@Html.Label("Error Code")
</span><span class="rightContent"><span id="ChildDialogLink" class="treeViewLink">Click
here to Select Error Codes</span>
<br />
<span id="ErrorCodeDisplay" style="cursor: pointer; text-decoration: underline;">@(Model.ErrorDescription)</span>
@Html.HiddenFor(model => model.ErrorDescription)
</span>
</div>
<div id="runDatestreeview" title="Dialog Title" style="font-size: 10px; font-weight: normal;
overflow: scroll; width: 400px; height: 450px;">
<table class="grid" style="width: 600px; margin: 3px 3px 3px 3px;">
<thead>
<tr>
<th>
Run Dates:
</th>
<th>
Minimum Replicate:
</th>
</tr>
</thead>
<tbody>
@Html.EditorFor(x => x.RunDatesDisplay)
</tbody>
</table>
</div>
<div class="bodyContent">
@if (Model.TestExceptionDisplay != null && Model.TestExceptionDisplay.Count() > 0)
{
<span class="leftContent">
@Html.Label("Test Exceptions")
</span><span class="rightContent"><span id="TestExceptionChildDialogLink" class="treeViewLink">
Click here to View Test Exceptions</span>
<br />
<span id="TestExceptionDisplayy"></span></span>
}
</div>
<div id="testExceptiontreeview" title="Dialog Title" style="font-size: 10px; font-weight: normal;
overflow: scroll; width: 800px; height: 450px; display: none;">
<table class="grid" style="width: 600px; margin: 3px 3px 3px 3px;">
<thead>
<tr>
<th>
Exception
</th>
<th>
Frequency
</th>
<th>
Comment
</th>
<th>
Replicate Range
</th>
</tr>
</thead>
<tbody>
@if (Model.TestExceptionDisplay != null)
{
@Html.EditorFor(x => x.TestExceptionDisplay)
}
</tbody>
</table>
</div>
<div class="bodyContent">
<span class="leftContent">
@Html.Label("Service Entry Request")
</span><span class="rightContent">
@Html.DropDownList("ServiceRequest", ListHelpers.YesNoList())
</span>
</div>
<div class="bodyContent">
<span class="leftContent">
@Html.Label("Problem Description")
</span><span class="rightContent">
@Html.TextArea("ProblemDescription", new { style = "width: 600px; height: 30px" })
</span>
</div>
if (Model.UserRole == "Admin" || Model.UserRole == "SuperUser")
{
<div class="bodyContent">
<span class="leftContent">
@Html.Label("Active")
</span><span class="rightContent">
@Html.CheckBoxFor(model => model.Active)
</span>
</div>
}
else
{
@Html.HiddenFor(model => model.Active)
}
<p>
<input id="LogType" type="hidden" value="Run" />
<input id="ID" type="hidden" value="0" />
@if (Model.ExitCode == "1")
{
@Html.Hidden("ExitCode", Model.ExitCode)
}
else
{
<input id="ExitCode" type="hidden" value='0' />
}
</p>
@Html.HiddenFor(model => model.MaxReplicateId)
@Html.HiddenFor(model => model.MinReplicateId)
@Html.HiddenFor(model => model.OutputFileName)
@Html.HiddenFor(model => model.OutputStoredFileName)
@Html.HiddenFor(model => model.LoadListFileName)
@Html.HiddenFor(model => model.LoadListStoredFileName)
@Html.HiddenFor(model => model.AttachedLogFileName)
@Html.HiddenFor(model => model.AttachedMultipleLogFileNames)
@Html.HiddenFor(model => model.MinTestCompletionDate)
@Html.HiddenFor(model => model.MaxTestCompletionDate)
@Html.HiddenFor(model => model.UserRole)
@Html.HiddenFor(model => model.Active)
<div class="bodyContent">
<span class="leftContent"></span><span class="rightContent">
<button id="submit" name="submit" class="art-button" type="submit" value="Create">
Create</button></span>
</div>
}
</div>
</fieldset>
<script src="@Url.Content("~/Scripts/exitCode.js")" type="text/javascript"></script>
<div id="treeview" title="Dialog Title" style="font-size: 10px; font-weight: normal;
overflow: scroll; width: 800px; height: 450px;">
<div id="errorCodes">
@Html.RenderTree(CacheHelper.ErrorCodes(), ec => ec.Name, ec => ec.Children.ToList(), ec => (ec.ID).ToString(), null, "e")
</div>
<div id="inputReps" style="display: none;">
</div>
</div>
控制器行动
[HttpPost]
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(RunLogEntry runLogEntry, String ServiceRequest, string Hour, string Minute, string AMPM,
string submit, IEnumerable<HttpPostedFileBase> file, String AssayPerformanceIssues1, List<string> Replicates)
{
#region LogFile_UserConfrimation
if (submit == null)
{
if (runLogEntry.RunDatesDisplay != null || runLogEntry.RunDatesDisplay.Count() > 0)
{
//1. Get The selected/Checked Run Dates
//2. Locate The Parsed File(s)
//3. Parse the File Again and populate fields
List<string> fileNames = new List<string>();
if (runLogEntry.AttachedLogFileName != null || runLogEntry.AttachedLogFileName != string.Empty)
{
if (runLogEntry.AttachedLogFileName.Contains(".zip") || (runLogEntry.AttachedLogFileName.Contains(".ZIP")))
{
string[] splitData = runLogEntry.AttachedMultipleLogFileNames.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
foreach (string s in splitData)
{
fileNames.Add(s);
}
}
else
{
fileNames.Add(runLogEntry.AttachedLogFileName);
}
}
foreach (var modelValue in ModelState.Values)
{
modelValue.Errors.Clear();
}
OutputResults or = FileImport.logfileOutput(fileNames, runLogEntry.RunDatesDisplay);
if (or != null && or.isValid == true)
{
ModelState.Remove("SPTestsCompleted");
ModelState.Remove("MinReplicateId");
ModelState.Remove("MaxReplicateId");
ModelState.Remove("OutputFileName");
ModelState.Remove("MinTestCompletionDate");
ModelState.Remove("MaxTestCompletionDate");
ModelState.Remove("SelectedAssayIDs");
ModelState.Remove("RunStatusID");
//ModelState.Remove("OutputStoredFileName");
runLogEntry.SPTestsCompleted = or.testsCompleted;
runLogEntry.MinReplicateId = or.minReplicateId;
runLogEntry.MaxReplicateId = or.maxReplicateId;
runLogEntry.MinTestCompletionDate = or.minCompletionDate;
runLogEntry.MaxTestCompletionDate = or.maxCompletionDate;
//runLogEntry.OutputFileName = file.ElementAt(1).FileName;
//runLogEntry.OutputStoredFileName = storedFileName;
//set run date
if (or.minimumDate.HasValue)
{
ModelState.Remove("Hour");
ModelState.Remove("Minute");
ModelState.Remove("AMPM");
ModelState.Remove("RunDate");
runLogEntry.RunDate = or.minimumDate.Value;
ViewBag.Hour = or.minimumDate.Value.ToString("%h");
ViewBag.Minute = or.minimumDate.Value.Minute;
ViewBag.AMPM = or.minimumDate.Value.ToString("tt");
}
if (or.testExceptions != null)
{
//ModelState.Remove("TestExceptionDisplay");
runLogEntry.TestExceptionDisplay = or.testExceptions;
//ViewBag.TestExceptions = or.testExceptions;
}
string moduleName = "";
//set module name
if (or.module != null)
{
ModelState.Remove("SystemID");
//string s = or.module.Trim('"', ' ', '\t');
switch (or.module.Trim('"', ' ', '\t'))
{
case "EP001":
runLogEntry.SystemID = 1;
moduleName = "EP001";
break;
case "EP002":
runLogEntry.SystemID = 2;
moduleName = "EP002";
break;
case "EP003":
runLogEntry.SystemID = 3;
moduleName = "EP003";
break;
case "EP004":
runLogEntry.SystemID = 4;
moduleName = "EP004";
break;
case "EP005":
runLogEntry.SystemID = 5;
moduleName = "EP005";
break;
case "EP006":
runLogEntry.SystemID = 6;
moduleName = "EP006";
break;
case "EP007":
runLogEntry.SystemID = 7;
moduleName = "EP007";
break;
}
ViewBag.SystemID = new SelectList(db.System1, "ID", "SystemFullName", runLogEntry.SystemID).OrderBy(l => l.Text);
}
//fetch corresponding assay ids
if (or.assayList != null && or.assayList.Count() > 0)
{
runLogEntry.SelectedAssayIDs = (from assays in db.Assay
where or.assayList.Contains(assays.AssayKey ?? 0)
select assays.ID).ToArray();
}
}
}
}
#endregion
// set runstatus if tc = tr
if (runLogEntry.SPTestsRequested != 0 && runLogEntry.SPTestsCompleted != 0 && runLogEntry.SPTestsRequested == runLogEntry.SPTestsCompleted)
{
runLogEntry.RunStatusID = 1;
ViewBag.RunStatusID = new SelectList(db.RunStatus, "ID", "RunStatusName", runLogEntry.RunStatusID).OrderBy(l => l.Text);
}
else
{
ViewBag.RunStatusID = new SelectList(db.RunStatus, "ID", "RunStatusName").OrderBy(l => l.Text);
}
//if (runLogEntry.SystemID == 0)
//{
// //viewbag.systemid = new selectlist((from asys in db.system1
// // where asys.active == true
// // select asys), "id", "systemfullname").orderby(l => l.text);
ViewBag.SystemID = new SelectList(db.System1, "ID", "SystemFullName", runLogEntry.SystemID).OrderBy(l => l.Text);
//}
ViewBag.OperatorID = new SelectList(db.User, "ID", "FullName").OrderBy(l => l.Text);
ViewBag.AssayID = new SelectList(db.Assay, "ID", "AssayFullName").OrderBy(l => l.Text);
//ViewBag.SystemID = new SelectList(db.System1, "ID", "SystemFullName").OrderBy(l => l.Text);
ViewBag.GroupID = new SelectList(db.Group1, "ID", "GroupName").OrderBy(l => l.Text);
ViewBag.LocationID = new SelectList(db.Location, "ID", "LocationName").OrderBy(l => l.Text);
ViewBag.RunTypeID = new SelectList(db.RunType, "ID", "RunTypeName").OrderBy(l => l.Text);
List<SelectListItem> ServiceRequest1 = new List<SelectListItem>();
ServiceRequest1.Add(new SelectListItem { Text = "No", Value = "N" });
ServiceRequest1.Add(new SelectListItem { Text = "Yes", Value = "Y" });
ViewData["ServiceRequest"] = (Object)ServiceRequest1;
return View(runLogEntry);
所以在上面的控制器操作中,#region LogFile_UserConfrimation是确认步骤,当用户单击对话框时,该区域被执行,它从对话框中接收复选框列表,然后我只处理这些选择并更新一个几个模型属性并返回视图
答案 0 :(得分:2)
您正在通过刷新页面来破坏对服务器进行ajax调用的目的。如果页面刷新是可接受的,您应该正常提交表单。否则,您应该使用从服务器返回的json,并使用jQuery将结果添加到DOM。
编辑:
假设服务器正在返回部分视图:
客户端javascript:
var RunDialog;
$(document).ready(function () {
RunDialog = $("#runDatestreeview").dialog({ closeOnEscape: true, stack: false, autoOpen: false, modal: false, resizable: false, draggable: true, title: "Select Run Dates:", width: 600, height: 500,
buttons: { Select: function () {
$.post("/RunLogEntry/Create",
$("#form").serialize(),
function (data) {
$("#main").html(data);
}, "html");
},
Cancel: function () {
$(this).dialog("close");
}
}
});
RunDialog.closest("div.ui-dialog").appendTo("#form");
$("#RunDatesChildDialogLink").click(function () {
RunDialog.dialog("open");
});
});
通过ajax调用的服务器端控制器操作:
[HttpPost]
public ActionResult Create(MyEditModel model)
{
// save edit model and create view model
return PartialView("_RunLogEntryPartialView", viewModel);
}
在原始视图中,#main为:
<div id="main">
@Html.Partial("_RunLogEntryPartialView", Model)
</div>
然后在“_RunLogEntryPartialView”里面只包含#main里面的html。
您使用json作为数据类型而不是html。此外,您需要使用控制器操作方法中的PartialView()而不是使用View()的常规视图返回局部视图。此外,您没有看到任何更改的原因很可能是因为您在设置main的html时使用了错误的选择器语法。你使用的是$('main')而不是$('#main')。