如何在mvc 4中为以下语句将值设置为零

时间:2015-05-06 11:11:32

标签: c# asp.net-mvc asp.net-mvc-4 razor

@Html.DropDownList("SID", new SelectList(@ViewBag.SiteTypes, "SID", "SiteName"), "-select SiteName-")

上面的下拉列表是从控制器绑定的。

1 个答案:

答案 0 :(得分:1)

如果您希望默认选项具有已定义的值,则需要先将其添加到选项中,然后再将其发送到视图,例如:

List<SelectListItem> yourOptions = db.tbl_Site
    .OrderBy(p => p.SID)
    .Select(p => new SelectListItem 
    {
        Text = p.Text, //whatever field is text
        Value = p.SID.ToString() //whatever field is the value
    })
    .ToList();
var placeHolder = new SelectListItem
{
    Text = "--select Site--",
    Value = "0"
};

yourOptions.Insert(0, placeHolder);
ViewBag.SiteTypes = yourOptions;

然后做:

@Html.DropDownList("SID", (SelectList)ViewBag.SiteTypes, "SID", "SiteName"))