我正在上课,如下
public class UserRoleModel
{
public string Role { get; set; }
public bool UserRole { get; set; }
}
和public UserRoleModel[] UserRoles { get; set; }
我的控制器如下:
public ActionResult CreateUser()
{
UserDetailsModel model = new UserDetailsModel();
return View(model);
}
[HttpPost]
public ActionResult CreateUser(UserDetailsModel model)
{
return View(model);
}
在我看来,我有
>@foreach (var item in Model.UserRoles)
{
name = "UserRoles"+ ".Value["+ i + "]";
id= "UserRoles" + "_Value[" + i++ + "]";
selected = item.UserRole ? "checked=\"checked\"" : "";
<p>
<input type="checkbox" name="@name" id="@id" @selected value="true" />
<label for="@id">@item.Role</label>
<input type="hidden" name="@name" value="false" />
</p>
}
尽管在我的视图中相应地显示了值,但UserRoles没有模型绑定。我缺少什么,或者有更好更清洁的方法吗?
答案 0 :(得分:21)
使用编辑器模板可以很好地实现这些功能。他们还避免您在意见中编写意大利面条代码。例如:
型号:
public class UserDetailsModel
{
public IEnumerable<UserRoleModel> Roles { get; set; }
}
public class UserRoleModel
{
public string Role { get; set; }
public bool UserRole { get; set; }
}
控制器:
public class HomeController : Controller
{
public ActionResult Index()
{
return View(new UserDetailsModel
{
// Fill with some dummy stuff
Roles = Enumerable.Range(1, 5).Select(x => new UserRoleModel
{
Role = "role " + x,
UserRole = false
})
});
}
[HttpPost]
public ActionResult Index(UserDetailsModel model)
{
return View(model);
}
}
查看(~/Views/Home/Index.cshtml
):
@model AppName.Models.UserDetailsModel
@using (Html.BeginForm())
{
@Html.EditorFor(x => x.Roles)
<input type="submit" value="OK" />
}
编辑模板(~/Views/Home/EditorTemplates/UserRoleModel.cshtml
):
@model AppName.Models.UserRoleModel
@Html.CheckBoxFor(x => x.UserRole)
@Html.LabelFor(x => x.Role, Model.Role)
@Html.HiddenFor(x => x.Role)
现在我称之为干净的东西。