asp.net-mvc - CheckboxFor 不绑定(bind)嵌套对象

标签 asp.net-mvc asp.net-mvc-3 razor binding checkbox

当在模型中嵌套的对象中定义属性时,CheckBoxFor 不受限制?

这是一个例子。我有一个 SearchOptions包含 List<Star> 的模型属性(property)。每个Star有一个数字、一个名字和一个 bool应该有界的属性:

public class SearchOptions
{

    public SearchOptions()
    {
        // Default values
        Stars = new List<Star>()
        {
            new Star() {Number=1, Name=Resources.Home.Index.Star1,
                IsSelected=false},
            new Star() {Number=2, Name=Resources.Home.Index.Star2,
                IsSelected=false},
            new Star() {Number=3, Name=Resources.Home.Index.Star3,
                IsSelected=true},
            new Star() {Number=4, Name=Resources.Home.Index.Star4,
                IsSelected=true},
            new Star() {Number=5, Name=Resources.Home.Index.Star5,
                IsSelected=true},
        };
    }

    public List<Star> Stars { get; set; }

}

在我的强类型 View ( SearchOptions )中,我循环遍历 Stars属性(property):
@using (Html.BeginForm("Do", "Home"))
{
    <fieldset>
        <legend>@MVC3TestApplication.Resources.Home.Index.Search</legend>
        @{ 
            foreach (Star s in Model.Stars)
           {
                @Html.CheckBoxFor(m => s.IsSelected)
                <label>@s.Name</label>

           }}
    </fieldset>
    <input type=submit value="Invia" />
}

Controller 的(相关部分)是:
    public ActionResult SearchOptions()
    {
        return View(new SearchOptions());
    }

    [HttpPost]
    public ActionResult Do(SearchOptions s)
    {
        // Do some stuff
        return View("SearchOptions", s);
    }

最佳答案

这是因为您如何访问 CheckBoxFor 中的属性。表达。

@for (int i = 0; i < Model.Stars.Count(); i++) { 
    @Html.CheckBoxFor(m => m.Stars[i].IsSelected)
    <label>@Model.Stars[i].Name</label>
}

这应该适合你。

以下是不同方法的输出:
//using the for loop
<input id="Stars_2__IsSelected" name="Stars[2].IsSelected" type="checkbox" value="true" />

//using the foreach
<input checked="checked" id="s_IsSelected" name="s.IsSelected" type="checkbox" value="true" />

您会注意到 foreach 不包含在进行模型绑定(bind)时与之匹配的正确名称。

关于asp.net-mvc - CheckboxFor 不绑定(bind)嵌套对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6781730/

相关文章:

asp.net-mvc - MVC方法从ListBoxFor方法输出无序列表

asp.net-mvc - MVC3 类验证属性

javascript - 在指令中定义 ng-model 后,Angularjs ng-model 不起作用

c# - 如何安排在我的 MVC 网络应用程序中自动运行 Controller ?

c# - asp.net MVC 嵌套模型绑定(bind)错误

asp.net-mvc - 部分验证 ASP.NET MVC

c# - 如何在 C# .NET Core 中测试查询的执行时间

asp.net-mvc - MVC 3 WebGrid Column 按字母顺序排序,而不是根据表结构

javascript - Vue.js - 在组件内部使用 unicode 语法渲染 Font Awesome 不起作用

c# - asp .net mvc 中的路由