ASP.NET MVC的CheckBoxList从列表属性模型 [英] ASP.NET MVC CheckBoxList from model with List Property

查看:108
本文介绍了ASP.NET MVC的CheckBoxList从列表属性模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

道歉,如果标题是不清楚。

Apologies if the title is unclear.

我试图从形式ASP.NET MVC提交返回我的模型。

I'm trying to return my model from a form submit in ASP.NET MVC.

我的问题是几乎相同的this问题,只有在不同我没有列表与LT;产品型号> 但就像一个模型:

My question is nearly the same as this question, only differing in that I don't have a List<Model> but a model like:

public Model
{
     string UserName {get; set;}
     string Password {get; set;}
     List<Roles> UserRoles {get; set;}
}

在我需要的作为的UserRole复选框的管理员可以从创建一个新用户时选择。我的问题是,我不知道该如何对一个列表中使用@ Html.CheckBoxFor。我想这样的:

where I need the UserRoles as checkboxes that the admin can select from when creating a new user. My question is, I'm unsure how to use a '@Html.CheckBoxFor' against a list. I tried this:

 @for (var i = 0; i < Model.UserRoles.Count();i++ )
 {
   @Html.HiddenFor(model => model.UserRoles[i].RoleID)
   @Html.CheckBoxFor(model => model.UserRoles[i].Selected)
   @Html.LabelFor(model => model.UserRoles[i].Name)
 }

这丝毫不工作 - 每个页面上的标签是名,而我的列表是在POST空。谁能给我提供这个任何指导?

which in no way worked - every label on the page is "Name", and my List was empty in the POST. Can anyone offer me any guidance on this?

推荐答案

没有必要从剃刀走的。

这对我的作品:

for (var i = 0; i < Model.UserRoles.Count(); i++)
{
    var role = Model.UserRoles[i];
    @Html.HiddenFor(model => model.UserRoles[i].RoleId)
    @Html.CheckBoxFor(model => model.UserRoles[i].Selected)
    @Html.LabelFor(model=> model.UserRoles[i].Name, role.Name)
}

这篇关于ASP.NET MVC的CheckBoxList从列表属性模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆