我对MVC很新,所以请耐心等待,但是我似乎无法在MVC 4回发期间将SelectList中的值绑定到所选对象的实例。
假设我必须创建一名教师作为学校的成员。我有一个ViewModel类定义如下:
public class RegisterTeacherModel
{
[Required]
[Display(Name = "User name")]
public string UserName { get; set; }
[Required]
[DataType(DataType.EmailAddress)]
[Display(Name = "Email address")]
public string Email { get; set; }
[Required]
[Display(Name = "School")]
public School SelectedSchool { get; set; }
[ScaffoldColumn(false)]
public Guid UserId
{
get;
set;
}
public SelectList PossibleSchools
{
get;
private set;
}
public RegisterTeacherModel(IRepository<School> schoolRepo)
{
PossibleSchools = new SelectList(schoolRepo, "Id", "Name");
}
}
我的观点:
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<legend>RegisterTeacherModel</legend>
<div class="editor-label">
@Html.LabelFor(model => model.UserName)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Email)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Email)
@Html.ValidationMessageFor(model => model.Email)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.SelectedSchool)
</div>
<div class="editor-field">
@Html.DropDownListFor(model => model.SelectedSchool, Model.PossibleSchools)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
最后,我的Controller方法:
[HttpPost, ActionName("Create")]
public ActionResult CreateTeacher(RegisterTeacherModel teacherModel)
{
if (ModelState.IsValid)
{
try
{
...
}
}
}
但是当我在Controller中的Create方法中收到RegisterTeacherModel对象时,SelectedSchool总是为null。我必须错过模型绑定器在回发时重新创建对象引用的方式。有人能指出我正确的方向吗?
答案 0 :(得分:3)
我想你在第二篇文章中提到了它:尝试将初始代码指向Model.SelectedSchool。<IdProperty>
<div class="editor-field">
@Html.DropDownListFor(model => model.SelectedSchool.**<IdProperty>**, Model.PossibleSchools)
</div>
答案 1 :(得分:2)
好吧,我找到了解决方法。我仍然不知道我是否遗漏了某些内容,但我没有在ViewModel中使用School对象,而是将其替换为SelectedSchoolId:
public class RegisterTeacherModel
{
[Required]
[Display(Name = "User name")]
public string UserName { get; set; }
[Required]
[DataType(DataType.EmailAddress)]
[Display(Name = "Email address")]
public string Email { get; set; }
[Required]
[Display(Name = "School")]
public int SelectedSchoolId { get; set; }
...
}
并更改我的“查看”下拉列表以改为使用此选项:
<div class="editor-field">
@Html.DropDownListFor(model => model.SelectedSchoolId, Model.PossibleSchools)
</div>
然后在我的控制器中,在创建真实模型对象时,我可以简单地从School存储库中取出School对象,并将其与真正的Teacher对象相关联。