SelectList问题(选定值)

时间:2015-08-27 01:57:53

标签: javascript twitter-bootstrap asp.net-mvc-4 jquery-chosen

我在Modal Bootstrap(5)中有几个DDL,而那些DDL与Controller中的Viewbag绑定,如下所示:

(适用控制器)

ViewBag.StateID = new SelectList(db.State, "StateID", "StateDesc", events.StateID);
ViewBag.CountryID = new SelectList(db.Country, "CountryID", "CountryDesc",events.CountryID);
ViewBag.HotelID = new SelectList(db.Hotel, "HotelID", "HotelDesc", events.HotelID);
ViewBag.AirportID = new SelectList(db.Airport, "AirportID", "AirportDesc", events.AirportID);
ViewBag.AirlineID = new SelectList(db.Airline, "AirlineID ", "AirlineDesc", events.AirlineID);

如果我的代码声明是这样的话,我的视图工作完全正常并填充DDL并显示所选项目:

(查看)

@Html.DropDownList("AirlineID", String.Empty)

(适用的Javascript)

<script type="text/javascript">
    $('#AirlineID').attr('class', 'chosen-select form-control required');
    $('#AirportID').attr('class', 'chosen-select form-control required');
    $('#StateID').attr('class', 'chosen-select form-control required');
    $('#CountryID').attr('class', 'chosen-select form-control required');
    $('#HotelID').attr('class', 'chosen-select form-control required');
</script>

但是,如果我的代码是以这种方式声明的,则不会显示Selected项目或Show:

@Html.DropDownList("AirportID", (IEnumerable<SelectListItem>)ViewBag.AirportID, String.Empty, new { @class = "chosen-select form-control required" })

我使用selected-select class

为什么?缺少声明或代码?错误的代码?

谢谢你

1 个答案:

答案 0 :(得分:1)

您不能对绑定的属性和SelectList

使用相同的名称
@Html.DropDownList("CountryID", (IEnumerable<SelectListItem>)ViewBag.CountryID, ...)

表示您绑定到名为CountryID的属性,但在您的情况下,CountryIDSelectList而不是值类型(并且<select>元素只能绑定到值类型。

该方法在内部生成<option>个元素的集合,并设置value属性和文本。当它这样做时,它会检查绑定到的属性的值。如果属性的值与选项的值匹配,则呈现selected="selected"属性。在您的情况下,CountryID不是一个int值,它与您在选项中生成的StateID值之一相匹配,因此selected="selected"永远不会在任何选项上设置,因为{的值{ {1}}是CountryID(不是"System.Web.Mvc.SelectList""1"等)

绑定到属性时,将忽略设置"2"构造函数的最后一个参数。

您可以通过将SelectList指定为第二个参数来完成此工作,这意味着帮助程序会回退到使用null作为第一个参数。

SelectList

但推荐的方法是使用视图模型,例如

@Html.DropDownList("CountryID", null, String.Empty, new { @class = "chosen-select form-control required" })

并在GET方法中初始化实例或视图模型,将数据模型属性映射到它并分配public class MyViewModel { [Display(Name = "Country")] [Required(ErrorMessage = "Please select a country")] public int CountryID { get; set; } public SelectList CountryList { get; set; } } 属性。然后在视图中,使用强类型的html帮助器绑定到模型属性。

SelectList
相关问题