asp.net mvc - DropDownList setting selected item in MVC5 -
how can set default value drowdownlist?
i have this:
@html.dropdownlistfor(model => model.businessid, (selectlist)viewbag.businesses, new { @class = "form-control" })
edit:
// get: reviews/create public actionresult create() { viewbag.businesses = new selectlist(db.businesses, "businessid", "businessname"); return view(); } [httppost] [validateantiforgerytoken] public actionresult create([bind(include = "reviewid,reviewtext,rating,businessid")] review review, int id) { if (modelstate.isvalid) { db.reviews.add(review); db.savechanges(); return redirecttoaction("details", "businesses", new { id = review.businessid }); } review.businessid = id; viewbag.businesses = new selectlist(db.businesses, "businessid", "businessname", review.businessid); return view(review); }
how call it:
@html.actionlink("write review", "create", "reviews", new { id = model.businessid }, null)
and point each businessid, has value, , call them let's /reviews/create/15, in case businessid 15. , when page loads, want item businessid 15 selected default. whenever load page, selects 1 lowest businessid.
update:
changing action solved problem:
public actionresult create(int? id) { viewbag.businesses = new selectlist(db.businesses, "businessid", "businessname", id); return view(); }
you should using typed versions, makes easier, , less error prone.
@html.dropdownlistfor(x => x.businessid, model.businesses, new { @class="form-control" })
here. model.businesses ienuerable (which can list, collection, array, etc..)
or can use viewbag, so:
@html.dropdownlistfor(x => x.businessid, viewbag.businesses, new { @class="form-control" })
now, i'm unclear on mean "default value" here. mean want set value value in database? in case, populate model.businessid value want set (make sure it's value, not text) , automatically select when renders page.
if mean want "select business..." use "option" overload:
@html.dropdownlistfor(x => x.businessid, viewbag.businesses, "select business...", new {@class="form-control" })
note: not name list of selectlistitems (or selectlist) same selected item property, ie.. not this:
@html.dropdownlistfor(x => x.businessid, viewbag.businessid, "select business...", new {@class="form-control" })
Comments
Post a Comment