来自具有 List 属性的模型的 ASP.NET MVC CheckBoxList [英] ASP.NET MVC CheckBoxList from model with List Property

查看:24
本文介绍了来自具有 List 属性的模型的 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.

我的问题与 这个问题,唯一的不同在于我没有 List 而是一个像这样的模型:

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

我需要 UserRoles 作为复选框,管理员可以在创建新用户时从中进行选择.我的问题是,我不确定如何对列表使用@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?

推荐答案

完全不需要离开 Razor.

No need to go away from Razor at all.

这对我有用:

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

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

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