Html.DropDownList默认值MVC 5

时间:2014-09-19 22:21:26

标签: c# asp.net-mvc-5

我只是想在这个列表中添加一个默认值(“Create new Venue”),这可能比我做的更容易。我对方法重载感到困惑,特别是因为我正在使用的(由脚手架创建)的重载是DropDownList(字符串名称,IEnumerable selectList,对象htmlAttributes),第二个参数是null,但它可以工作。我认为这里有一些惯例。任何人都可以阐明这一点和/或我如何在此列表中添加默认值?

控制器:

ViewBag.VenueId = new SelectList(db.Venues, "Id", "Name", review.VenueId);
        return View(review);
    }   

查看:

<div class="form-group">
        @Html.LabelFor(model => model.VenueId, "VenueId", htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownList("VenueId", null, htmlAttributes: new { @class = "form-control" })
            @Html.ValidationMessageFor(model => model.VenueId, "", new { @class = "text-danger" })
            <div>Don't see what you're looking for?  Fear not.  Just type in the name and create your review; we'll fill in the rest!</div>
        </div>
</div>

1 个答案:

答案 0 :(得分:1)

也许您可以分解您的SelectList并将项目插入其中?这是一个例子(没有测试过,所以不是100%确定它有效):

控制器

// Create item list from your predefined elements
List<SelectListItem> yourDropDownItems = new SelectList(db.Venues, "Id", "Name", review.VenueId).ToList();

// Create item to add to list
SelectListItem additionalItem = new SelectListItem { Text = "Create new Venue", Value = "0" }; // I'm just making it zero, in case you want to be able to identify it in your post later

// Specify index where you would like to add your item within the list
int ddIndex = yourDropDownItems.Count(); // Could be 0, or place at end of your list?

// Add item at specified location
yourDropDownItems.Insert(ddIndex, additionalItem);

// Send your list to the view
ViewBag.DropDownList = yourDropDownItems;

return View(review);

查看

@Html.LabelFor(model => model.VenueId, new { @class = "form-control" })
    <div>
        @Html.DropDownListFor(model => model.VenueId, ViewBag.DropDownList)
        @Html.ValidationMessageFor(model => model.VenueId)
    </div>
</div>

编辑:

你应该能够添加默认值的一种方法是在.DropDownListFor的最后一个参数中,如下所示:

@Html.DropDownListFor(model => model.VenueId, ViewBag.DropDownList, "Create new Venue")