我有一个模型如下:
public class RegisterModel
{
[Required]
[Display(Name = "User name")]
public string UserName { get; set; }
[Required]
[DataType(DataType.Password)]
public string Password { get; set; }
public virtual Department Department { get; set; }
}
这是控制器动作:
[AllowAnonymous]
public ActionResult Register(int departmentId)
{
using (var db = new DataContext())
{
var department = db.Departments.Find(departmentId);
var registerModel = new RegisterModel {Department = department};
return View(registerModel);
}
}
我有部门列表页面。比如 Foo,那么我想将用户添加到 Foo。
1 . Foo - add user
然后我有一个注册视图。
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
@Html.ValidationSummary()
@Html.HiddenFor(x => x.Department.Id)
<fieldset>
<legend>Registration Form</legend>
<ol>
<li>
@Html.LabelFor(m => m.UserName)
@Html.TextBoxFor(m => m.UserName)
</li>
<li>
@Html.LabelFor(m => m.Password)
@Html.PasswordFor(m => m.Password)
</li>
</ol>
<input type="submit" value="Register" />
</fieldset>
}
现在我的问题是如何将部门绑定到模型?与部门 ID?还是部门对象?
我可以访问从数据库填充的部门,然后我需要将其传递给 View。但我该如何通过呢?所以在注册提交后,我可以访问它或它的ID吗?