Reputation: 258
I'm just trying to add a default value ("Create new Venue") to this list and it's probably easier than I'm making it. I'm confused by the method overloads, particularly because the overload I'm using (created by scaffolding) is DropDownList(string name, IEnumerable selectList, object htmlAttributes) and the second parameter is null, but it works. I think there is some convention at work here. Can anyone shed light on that and/or how I can add a default value to this list?
Controller:
ViewBag.VenueId = new SelectList(db.Venues, "Id", "Name", review.VenueId);
return View(review);
}
View:
<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>
Upvotes: 2
Views: 6128
Reputation: 96
Maybe you can break down your SelectList and insert an item into it? Here's an example (haven't tested it out, so not 100% sure it works):
Controller
// 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);
View
@Html.LabelFor(model => model.VenueId, new { @class = "form-control" })
<div>
@Html.DropDownListFor(model => model.VenueId, ViewBag.DropDownList)
@Html.ValidationMessageFor(model => model.VenueId)
</div>
</div>
Edit:
One way you should be able to add a default value is in the last parameter of .DropDownListFor, like this:
@Html.DropDownListFor(model => model.VenueId, ViewBag.DropDownList, "Create new Venue")
Upvotes: 2