CheckBoxList multiple selections: difficulty in model bind back

后端 未结 1 532
盖世英雄少女心
盖世英雄少女心 2020-12-28 22:30

I am having a class as follows

 public class UserRoleModel
{
    public string Role { get; set; }
    public bool UserRole { get; set; }
}

相关标签:
1条回答
  • 2020-12-28 23:10

    Those kind of things are nicely achieved with editor templates. They also avoid you from writing spaghetti code in your views. Example:

    Model:

    public class UserDetailsModel
    {
        public IEnumerable<UserRoleModel> Roles { get; set; }
    }
    
    public class UserRoleModel
    {
        public string Role { get; set; }
        public bool UserRole { get; set; }
    }
    

    Controller:

    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);
        }
    }
    

    View (~/Views/Home/Index.cshtml):

    @model AppName.Models.UserDetailsModel
    @using (Html.BeginForm())
    { 
        @Html.EditorFor(x => x.Roles)
        <input type="submit" value="OK" />
    }
    

    Editor template (~/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)
    

    Now that's what I call clean stuff.

    0 讨论(0)
提交回复
热议问题