我的模型看起来像这样:
public class UserAdminEditViewModel
{
public User User { get; set; }
public IEnumerable<Usergroup> Usergroups { get; set; }
public IList<int> UsergroupID { get; set; }
public UserAdminEditViewModel() {}
}
我的视图看起来像这样:
“%&gt; USEREDIT<% using (Html.BeginForm()) {%>
<fieldset>
<legend>Fields</legend>
<p>
<label for="Username">Användarnamn: *</label>
<%= Html.TextBox("Username", Model.User.Username) %>
<%= Html.ValidationMessage("Username", "*") %>
</p>
<p>
<label for="Firstname">Förnamn: *</label>
<%= Html.TextBox("Firstname", Model.User.Firstname) %>
<%= Html.ValidationMessage("Firstname", "*") %>
</p>
<p>
<label for="Surname">Efternamn: *</label>
<%= Html.TextBox("Surname", Model.User.Surname) %>
<%= Html.ValidationMessage("Surname", "*") %>
</p>
<p>
<label for="Email">E-post: *</label>
<%= Html.TextBox("Email", Model.User.Email) %>
<%= Html.ValidationMessage("Email", "*") %>
</p>
<p>
<label for="Password">Lösenord: *</label>
<%= Html.TextBox("Password", Model.User.Password) %>
<%= Html.ValidationMessage("Password", "*") %>
</p>
<p>
Användargrupper: <br />
<%= Html.CheckBoxList(Model.Usergroups.Select(ug => ug.UsergroupID.ToString()), Model.Usergroups.Select(ug => ug.UsergroupName), "UsergroupID") %>
</p>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
<% } %>
<div>
<%=Html.ActionLink("Tillbaka till användare", "Users") %>
</div>
我的控制器如下:
public ActionResult UserEdit(int? userID)
{
User u;
if (userID == null)
{
u = new User();
}
else
{
u = us.GetUsers(userID.Value).SingleOrDefault();
}
return View("UserEdit", new UserAdminEditViewModel { User = u, Usergroups = ug.GetUsergroups() });
}
[AcceptVerbs(HttpVerbs.Post)]
//public ActionResult UserEdit([BindAttribute(Include = "Firstname,Surname,Username,Email,Password,UserID,UsergroupID")]User userobj, IList<int> UsergroupID)
public ActionResult UserEdit(UserAdminEditViewModel userobj)
{
if (ModelState.IsValid)
{
try
{
//userobj.UsersUsergroups = new UsersUsergroup { UsergroupID = UsergroupID.ToList() };
//us.SaveUser(userobj);
}
catch
{
ModelState.AddModelError("SomeError", "errrrrrrrrror");
}
}
return View();
//return View("UserDetail", new UserAdminEditViewModel { User = userobj });
}
问题:
如果我使用我创建的UserAdminEditViewModel,则只设置IList UsergroupID的值(这是一个名为UsergroupID的复选框列表)。如果我使用User类,我可以访问所有用户属性,因为firstname等已被填写。
为什么用户对象不会在帖子上的UserAdminEditViewModel中填充?什么不见了?
提前致谢 / M
编辑:
视图强烈输入“BookingSystem.MVC.ViewModels.UserAdminEditViewModel”
无法在此编辑器中显示
答案 0 :(得分:0)
使用
<%= Html.TextBox("User.Firstname", Model.User.Firstname) %>
。签入渲染视图。 Formfields应呈现:
<input type="text" name="User.Firstname" />