c# - asp.net MVC 4 - output list of checkbox items, associate selections with user - allow display & editing later -


asp.net c# mvc 4 code first application - in visual studio 2012 express, sql server 2012 express.

i have places object. output name of places in list - check box next each.

i logged in users select places - , have saved. later can login , see them again, appropriate check boxes selected.

what best approach? i'm new mvc , not sure of best practice here.

thanks

update

the below checkboxlistfor helper worked great, though wasn't obvious how process user selection (it returns list of ids).

i created below take list of ids - convert list of objects, , add selectecities list in view model. select checkboxes user selected before page posted:

public actionresult examples(postedcities postedcities) {  // viewmodel  citiesviewmodel cvm = new citiesviewmodel();   // create list of cities  list<city> cities = new list<city>{   new city { id = 1, name = "london"},   new city { id = 2, name = "saigon"},   new city { id = 3, name = "new york"}  };   // assign list of cities viewmodel   cvm.availablecities = cities;   // if posted cities present, user posted (else first call)  if (postedcities.cityids != null)  {     // temporary city object     city cty = new city();      // list of selected cities     list<city> selcities = new list<city>();      // go through each postedcity id     foreach (string s in postedcities.cityids)     {        // id of postedcity        int idsel = convert.toint32(s);         // lookup city id in cities        cty = cities.single(c => c.id == idsel);         // add selected city cty object        selcities.add(cty);     }      // fill cvm.selectedcities selcities     cvm.selectedcities = selcities;  }  return view(cvm); } 

this works - approach or have overcomplicated it? or done badly?

you can save work , use existing mvccheckboxlist library.

install nuget using command:

pm> install-package mvccheckboxlist 

here home page: mvccheckboxlist
, here documentation: mvccheckboxlist/documentation

other solutions require ugly coding.

update

as klas mellbourn suggested (i'm sorry taking granted) view model list best practice such sceneria. documentation link provided contains such examples understand more easily.


Comments

Popular posts from this blog

SPSS keyboard combination alters encoding -

Add new record to the table by click on the button in Microsoft Access -

javascript - jQuery .height() return 0 when visible but non-0 when hidden -