javascript - How to select object in dropdown -
i have city class
public class city { public int id { get; set; } public string name { get; set; } public string countrycode { get; set; } }
and ride class.
public class ride { public guid id { get; set; } public city { get; set; } public list<city> { get; set; } public datetime dateandtime { get; set; } }
what best way load cities, pass view, show them in dropdownlists , post data controller? best if add more 1 city to column. have found selectize.js have no experience javascript. can pass options json etc or list of cities database.
thank time.
you'll need view model, if want select multiple cities @ once. example:
public class rideviewmodel { public guid id { get; set; } public datetime dateandtime { get; set; } public int fromcityid { get; set; } public list<int> tocityids { get; set; } public ienumerable<selectlistitem> citychoices { get; set; } }
notice there's no list<city>
property on view model. instead, there's tocityids
store selected id values list box , citychoices
used populate list box. can't post full city
objects list box, simple types int
. so, on post you'll use values tocityids
lookup city
instances database. same goes from
property on entity.
now, in controller:
private void populatecitychoices(rideviewmodel model) { model.citychoices = db.cities.select(m => new selectlistitem { value = m.id, text = m.name }); } public actionresult create() { var model = new rideviewmodel(); populatecitychoices(model); return view(model); } [httppost] public actionresult create(rideviewmodel model) { if (modelstate.isvalid) { // create new `ride` , map data on model var ride = new ride { id = guid.newguid(), dateandtime = model.dateandtime, = db.cities.find(model.fromcityid), = db.cities.where(m => m.tocityids.contains(m.id)) } db.rides.add(ride); db.savechanges(); } // must repopulate `citychoices` after post if need return form // view again due error. populatecitychoices(model); return view(model); }
finally in view change model declaration to:
@model namespace.to.rideviewmodel
and add from
select list , to
list box:
@html.dropdownlistfor(m => m.fromcityid, model.citychoices) @html.listboxfor(m => m.tocityids, model.citychoices)
you can use same choices both, since they're both selecting cities.
Comments
Post a Comment