加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc – Checkbox不与嵌套对象绑定

发布时间:2020-12-16 06:46:08 所属栏目:asp.Net 来源:网络整理
导读:在嵌套在模型中的对象中定义属性时,CheckBoxFor不受限制? 这是一个例子.我有一个SearchOptions模型,其中包含List Star属性.每颗星都有一个数字,一个名字和一个应该受限制的bool属性: public class SearchOptions{ public SearchOptions() { // Default val
在嵌套在模型中的对象中定义属性时,CheckBoxFor不受限制?

这是一个例子.我有一个SearchOptions模型,其中包含List< 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,new Star() {Number=3,Name=Resources.Home.Index.Star3,IsSelected=true},new Star() {Number=4,Name=Resources.Home.Index.Star4,new Star() {Number=5,Name=Resources.Home.Index.Star5,};
    }

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

}

在我的强类型视图(SearchOptions)中,我循环遍历Stars属性:

@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" />
}

控制器的(相关部分)是:

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" />

您会注意到for foreach在进行模型绑定时不包含与其匹配的正确名称.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读