我在视图中有以下控件:
<div class="editor-label">
@Html.LabelFor(model => model.Number)
</div>
<div class="editor-field">
@Html.HiddenFor(model => model.Number)
@Html.TextBoxFor(model => model.Number, new { disabled = "disabled" })
</div>
<div class="editor-label">
@Html.LabelFor(model => model.ProjectID)
</div>
<div class="editor-field">
@Html.DropDownListFor(model => model.Project.ID, Model.ProjectList, "Select", new { onchange = "SelectedIndexChanged()" })
</div>
我在下拉列表值更改时提交表单以生成模型的Number字段,然后重新加载视图。如果没有HiddenFor控件,则在TextBoxFor中正确显示模型的编号。当我添加HiddenFor控件时,虽然Model.Number不为null,但不会显示Number字段。
这是什么原因?
我想要一个带有Number值的HiddenFor的原因是当我提交表单进行保存时,model.Number等于null。我想通过将值放在HiddenFor中我可以访问它...
编辑:控制器方法
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult CreateOpportunity(CreateEditOpportunityModel model)
{
// if the submit is made by the ddl
if (model.SubmitValue.Equals("ChangeProject"))
{
Project parentProject = pCtx.Projects.Find(model.Project.ID);
if (parentProject != null)
{
// Generate the "Number field"
Region projectRegion = rCtx.Regions.Find(parentProject.RegionID);
int numOpportunity = oCtx.Opportunitites.Count(o => o.ProjectID == parentProject.ID);
numOpportunity++;
string oppNumber = numOpportunity < 10 ? "0" + numOpportunity : numOpportunity.ToString();
model.Number = projectRegion.Name + "-" + parentProject.ID + "-" + oppNumber;
}
// Repopulate the ddl
model.ProjectList = new SelectList(pCtx.Projects, "ID", "ID");
return View(model);
}
// if submit is made by the save button
else if (model.SubmitValue.Equals("CreateOpportunity"))
{
if (ModelState.IsValid)
{
Opportunity opportunity = new Opportunity();
opportunity.ID = model.ID;
opportunity.Number = model.Number;
opportunity.ActivationDate = model.ActivationDate;
opportunity.Assignee = model.Assignee;
opportunity.Comments = model.Comments;
opportunity.CreationDate = DateTime.Now;
opportunity.LicenseFilePath = model.LicenseFilePath;
opportunity.LicenseRequestFilePath = model.LicenseRequestFilePath;
opportunity.OkPermanentStatus = model.OkPermanentStatus;
opportunity.PaidStatus = model.PaidStatus;
opportunity.PartNumber = model.PartNumber;
opportunity.Project = pCtx.Projects.Find(model.Project.ID);
//tell EF that Project already exists in Company table
oCtx.Entry(opportunity.Project).State = EntityState.Modified;
// Saves project
oCtx.Opportunitites.Add(opportunity);
oCtx.SaveChanges();
return RedirectToAction("Index");
}
model.ProjectList = new SelectList(pCtx.Projects, "ID", "ID");
return View(model);
}
model.ProjectList = new SelectList(pCtx.Projects, "ID", "ID");
return View(model);
}
这部分代码运行正常,我只是把它放在这里澄清事情。