asp.net – CheckBoxList多个选择:难度模型绑定

我正在上课,如下
public class UserRoleModel
{
    public string Role { get; set; }
    public bool UserRole { get; set; }
}

和public UserRoleModel [] UserRoles {get;组; }

我的控制器如下:

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没有模型绑定.我失踪了还是有更好更干净的方法

解决方法

使用编辑器模板很好地实现了这些事情.他们也避免你在你的意见中写意大利面条代码.例:

模型:

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)

在这就是我所说的干净的东西.

相关文章

这篇文章主要讲解了“WPF如何实现带筛选功能的DataGrid”,文...
本篇内容介绍了“基于WPF如何实现3D画廊动画效果”的有关知识...
Some samples are below for ASP.Net web form controls:(fr...
问题描述: 对于未定义为 System.String 的列,唯一有效的值...
最近用到了CalendarExtender,结果不知道为什么发生了错位,...
ASP.NET 2.0 page lifecyle ASP.NET 2.0 event sequence cha...