首页 文章

不绑定到模型属性mvc3的下拉列表

提问于
浏览
1

MVC3 DropdownListFor不将模型属性绑定到选定值这是我的视图

@{var items = new List<SelectListItem>(){
                            new SelectListItem {Text = "2", Value = "2", Selected = true},
                            new SelectListItem {Text = "3", Value = "3", Selected = false},
                            new SelectListItem {Text = "4", Value = "4", Selected = false},
                            new SelectListItem {Text = "5", Value = "5", Selected = false}
                        };

        }   
@Html.DropDownListFor(x => x.InvoiceItem.Count, new SelectList(items, "Value", "Text"))

InvoiceModel有一个名为InvoiceItem类的属性,它还具有int类型的属性Count . count属性始终为0,并且未更新为从下拉列表中选择的值 .

请帮助我已经花了好几个小时 . 谢谢 .


感谢您的回复 . 但我仍然有这个问题 .

我使用了@ Html.DropDownListFor(x => x.InvoiceItem.Count,new SelectList(items,“value”,“text”,2))

还尝试了@ Html.DropDownListFor(x => x.InvoiceItem.Count,new SelectList(items,“value”,“text”,“2”))

Count属性总是0.我在这里缺少什么 .

4 回答

  • 0

    也许你的问题跟我的一样 . 请检查 x.InvoiceItem.Count 是属性还是字段 . 如果是字段,则后期数据不会绑定到该字段 .

    My model

    public class SearchReportObject
    {
        public string report_type;
    }
    

    In cshtml

    @Html.DropDownListFor(model => model.report_type, new SelectList( new List<Object>{new { value = "0" , text = "Red"  },new { value = "1" , text = "Blue" },new { value = "2" , text = "Green"}} , "value", "text"))
    

    在帖子表单上, report_type 的值始终为 null . 但是当我将 report_type 从一个字段更改为这样的属性时:

    public class SearchReportObject
    {
        public string report_type{ set; get; }
    }
    

    它工作正常 .

  • 1

    使用:

    new SelectList(items, "value", "text", selectedvalue);
    

    例如:

    @{var items = new List<SelectListItem>(){
                                    new SelectListItem {Text = "2", Value = "2"},
                                    new SelectListItem {Text = "3", Value = "3"},
                                    new SelectListItem {Text = "4", Value = "4"},
                                    new SelectListItem {Text = "5", Value = "5"}
                                };
    
                }   
        @Html.DropDownListFor(x => x.InvoiceItem.Count, new SelectList(items, "Value", "Text", 2))
    
  • 2

    这是因为Model.InvoiceItem.Count(DropDownListFor中的第一个参数)的当前值覆盖了SelectList中的选定值 .

    这样就可以使用视图模型当前值来在模型错误之后设置此值 .

    Cyberdrew已经发布了这个问题的解决方案,你必须使用SelectList构造函数的第三个参数,它代表默认的选择值:

    @Html.DropDownListFor(x => x.InvoiceItem.Count, new SelectList(items, "Value", "Text", 2))
    
  • 0

    我想出了这个问题 . 我没有在保存按钮单击事件中将下拉列表发布到控制器 .

相关问题