我在一个Modal Bootstrap (5)中有几个DDL,那些DDL绑定了来自Controller的View袋,如下所示:
(控制器)
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并显示选定的项:
(View)
@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>但是,如果我的代码是以这种方式声明的,则所选项不会出现或显示:
@Html.DropDownList("AirportID", (IEnumerable<SelectListItem>)ViewBag.AirportID, String.Empty, new { @class = "chosen-select form-control required" })我使用选择的类。
为什么会这样呢?失踪申报书还是法典?密码错了?
谢谢你
发布于 2015-08-27 02:40:40
绑定到的属性和SelectList不能同时使用相同的名称。
@Html.DropDownList("CountryID", (IEnumerable<SelectListItem>)ViewBag.CountryID, ...)意味着绑定到名为CountryID的属性,但在这种情况下,CountryID是SelectList而不是值类型( <select>元素只能绑定到值类型)。
在内部,该方法生成<option>元素的集合,并设置value属性和文本。在此过程中,它将检查绑定到的属性的值。如果属性值与选项的值匹配,则呈现selected="selected"属性。在您的示例中,CountryID不是一个int值,它与您在选项中生成的StateID值之一相匹配,因此selected="selected"永远不会设置在任何选项上,因为CountryID的值是"System.Web.Mvc.SelectList" (而不是"1"或"2"等)。
在绑定到属性时,只需忽略设置SelectList构造函数的最后一个参数。
您可以通过将null指定为第二个参数来完成这项工作,这意味着助手返回到使用SelectList作为第一个参数。
@Html.DropDownList("CountryID", null, String.Empty, new { @class = "chosen-select form-control required" })但是,推荐的方法是使用视图模型,例如
public class MyViewModel
{
[Display(Name = "Country")]
[Required(ErrorMessage = "Please select a country")]
public int CountryID { get; set; }
public SelectList CountryList { get; set; }
}在GET方法中,初始化实例或视图模型,将数据模型属性映射到它并分配SelectList属性。然后,在视图中,使用强类型的html帮助程序绑定到模型属性。
@Html.LabelFor(m => m.CountryID)
@Html.DropDownListFor(m => m.CountryID, Model.CountryList, "-Please select-", new { @class="..." })
@Html.ValidationMessageFor(m => m.CountryID)https://stackoverflow.com/questions/32239473
复制相似问题