我正在通过两个值搜索数据库:
public class SearchProjectModel : ISearchProject
{
public int ProjectID { get; set; }
[Display(Name = "Project Number")]
public string JobNumber { get; set; }
[Display(Name = "Project Name")]
public string JobName { get; set; }
}
索引视图:
@model SearchProjectModel
@using (@Html.BeginForm("ManipulateProject", "Project", FormMethod.Post))
{
<div>
@Html.HiddenFor(x => x.ProjectID)
<div class="col-md-3">
@Html.LabelFor(x => x.JobNumber)
@Html.TextBoxFor(x => x.JobNumber, new { @class = "form-control", id = "jobNumber" })
@Html.ValidationMessageFor(x => x.JobNumber)
</div>
<div class="col-md-6">
@Html.LabelFor(x => x.JobName)
@Html.TextBoxFor(x => x.JobName, new { @class = "form-control " })
@Html.ValidationMessageFor(x => x.JobName)
</div>
</div>
<div class="col-md-12 text-center" style="margin-top: 1%">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
}
在控制器上,我根据找到的内容创建一个新模型:
public ActionResult ManipulateProject(SearchProjectRequest request)
{
var project = _projectService.GetBy(request);
if (project != null)
{
//When this method is complete the data is in the new model!!!!
return View("Project", Assemble(project));
}
return View("Project", Assemble(new ManipulateProjectModel()));
}
型号:
public class ManipulateProjectModel : IProject
{
public int ProjectID { get; set; }
[Display(Name = "Project Number"), Required(ErrorMessage = "Required!")]
public string JobNumber { get; set; }
[Display(Name = "Project Name"), Required(ErrorMessage = "Required!")]
public string JobName { get; set; }
//Lots of stuff that is being populated
}
项目视图:
@model ManipulateProjectModel
<div>
@using (@Html.BeginForm("Save", "Project", FormMethod.Post))
{
@Html.HiddenFor(x => x.ProjectID)
<div class="col-md-12" style="border: 1px dotted black; padding: 1%; margin-top: 1%">
<h3 class="col-md-12 text-center">Project Info</h3>
<div class="col-md-3">
@Html.LabelFor(x => x.JobNumber)
@Html.TextBoxFor(x => x.JobNumber, new { @class = "form-control", id = "jobNumber"})
@Html.ValidationMessageFor(x => x.JobNumber)
</div>
<div class="col-md-6">
@Html.LabelFor(x => x.JobName)
@Html.TextBoxFor(x => x.JobName, new { @class = "form-control "})
@Html.ValidationMessageFor(x => x.JobName)
</div>
//stuff that is populated just fine
</div>
}
</div>
当找到项目并调用Assemble时,新模型将填充所有数据!但是如果我只搜索了两个参数中的一个,那么我没有填写的框就会填充在模型上,但文本框不会显示数据。
为什么要填充模型,但视图不会填充文本框。它不应该知道或关心是否填充了上一个视图。
答案 0 :(得分:0)
这是因为html帮助程序使用ModelState
中的值,而不是模型中的值。当您发布到public ActionResult ManipulateProject(SearchProjectModel request)
时(请注意,我认为它真的是SearchProjectModel
,而不是SearchProjectRequest
),会创建SearchProjectModel
的实例并绑定其属性。这些值也会添加到ModelState
。
当您返回包含ManipulateProjectModel
实例的视图时,@Html.TextBoxFor(x => x.JobName
}会先通过查找ModelState
值来设置值。由于第一种形式的值是(比方说)null
,因此文章框会在帖子后显示空字符串,因为ModelState
的{{1}}值为JobName
,尽管您null
方法可能将其设置为什么。 {O-3}中解释了导致此行为的原因。
一种选择是为Assemble()
属性提供SearchProjectModel
中属性的不同名称。另一个选项是在重新分配新值并返回视图
ManipulateProjectModel
ModelState
注意清除模型状态也会删除验证错误,因此请谨慎使用。