在 MVC3 中,我试图让我的下拉列表的值为零,而不是起始"Please Select ..."的空字符串



我如何将第一个选项值获得为零而不是空字符串。因此,当用户goest到表单,也不选择任何值将通过零之类的值。我是MVC的新手,并花了一些时间试图找到一个简单的答案。这可以在jQuery中完成吗?任何建议都将不胜感激。

我的观点

@Html.DropDownListFor(x => x.ItemCatId,
 new SelectList(Model.CategoryddList, "Value", "Text"),
 "Select Category")

和控制器

items.CategoryddList =
        itemsRepository.GetItemDdl("Item Categories").Select(c => new SelectListItem 
                        {
                           Value = c.DropdownID.ToString(),
                           Text = c.DropdownText
                        });  

像许多问题一样,有很多方法可以做到这一点。jQuery和JavaScript是一种选择。对我而言,最快(懒惰)的方式是在列表顶部添加一个额外的项目,并带有"请选择"的值。我不知道您的外墙是如何工作的,但应该像这样

items.CategoryddList = new Category( null , 0, “Please Select …”); //add the default
//rest of your code
items.CategoryddList =
    itemsRepository.GetItemDdl("Item Categories").Select(c => new SelectListItem 
                    {
                       Value = c.DropdownID.ToString(),
                       Text = c.DropdownText
                    });  

记住,您也必须在HTTPPOST动作中处理该案例。

另一种方法是不使用razor @html.dropdownlistfor并使用其中的html,其中有一个foreach。 我将尝试查找其他方法以稍后执行此操作

编辑:这是从视图中执行此操作的另一种方法(我现在找不到快速的jQuery代码)。尝试以下操作:

<select name="FOOName"  id="FOOName" onchange="test(this)">
   <option value=""> Please Select</option>
   @{ foreach (var type in Model.CategoryddList)
   { 
    <option value="@type.Value"> @type.Text </option>
   }
}
</select> 

最新更新