c# - How to use dropdownlists in ASP.NET MVC with lookup values without ViewBag? -
this should easy, , can't life of me realize haven't found answers despite @ least hour of googling. anyway, here go:
i want create simple asp.net mvc view dropdowns allow user select values, saved id:s database. i've been told viewbag/viewdata devils work i've tried solve adding selectlist (view)model like:
public virtual selectlist accommodations { get; set; }
and in controller fill like:
loanapplication theloanapplication = new loanapplication(); theloanapplication.accommodations = new selectlist(db.accommodations.tolist(), "accommodationid", "name");
and in view use working:
@html.dropdownlistfor(model => model.accommodationid, model.accommodations, "choose accommodation")
this works should, when try save model, errors accommodations property (the list) null kind of expected. else in model should though.
i've looked @ known "countoso university" code example on asp.net site , in seem use viewbag solve similar problems. viewbag isn't bad use in scenario , might best possible solution? if not, prefered way solve problem , not use viewbag/viewdata?
thank you.
in controller post action, reload accommodations
list db in action.
you'd if modelstate
has errors , want pass these view, otherwise there's no need reload select list. you've not specified gives null reference, i'm assuming when have modelstate errors , reloading view show server-side errors. eg:
[httppost] public actionresult editaccommodation(accommodationviewmodel model) { if (!modelstate.isvalid) { model.accommodations = new selectlist(db.accommodations.tolist(), "accommodationid", "name"); return view(model); } // else modelstate ok , model.accommodationid set ... }
as aside, recommend keep variable names clear, eg:
public virtual selectlist accommodationselectlist { get; set; }
then, when refer accommodations
it's clear if it's select list (which isn't list of accommodations, it's list of select items) or real list of accommodations database.
Comments
Post a Comment