Simple DropDownList in ASP.NET MVC3 app -
i need simple dropdownlist in form , don't want create viewmodel. have 2 models(tables) in relation 1:n:
public class course { public int id { get; set; } public string name { get; set; } }
and
public class project { public int id { get; set; } public int courseid { get; set; } public int projectno { get; set; } public string name { get; set; } public datetime deadline { get; set; } }
in 'create project' want have dropdownlist id (as value) , name(as text) course table(model). in new project insert chosen courseid. how can simple possible?
any particular reason why don't want use viewmodel? they're helpful type of problem.
if don't want use viewmodel, can construct specific class in controller aggregate of properties need both classes:
public actionresult show(int id) { course course = repository.getcourse(id); // whatever persistence logic here project project = projectrepository.getprojectbycourseid(id); string coursename = c in course c.id == project.courseid select c.name; ienumerable<selectlistitem> selectlist = c in course select new selectlistitem { selected = (c.id == project.courseid), text = c.name, value = project.courseid.tostring() }; //add selectlist model here. return view(); //add model view , return it. }
it far easier have viewmodel this, have typed view. let me show you:
public class projectcourseviewmodel { public selectlist projectcourselist {get; private set; } public project project {get; private set; } public course course {get; private set; } public projectcourseviewmodel(project project, course course) { projectcourselist = getprojectcourseselectlist(project, course) project = project; course = course; } private selectlist getprojectcourseselectlist(project project, course course) { ienumerable<selectlistitem> selectlist = c in course select new selectlistitem { selected = (c.id == project.courseid), text = c.name, value = project.courseid.tostring() }; } }
and controller simple:
public actionresult show(int id) { course course = repository.getcourse(id); project project = projectrepository.getprojectbycourseid(id); projectcourseviewmodel pcvm = new projectcourseviewmodel(project, course) return view(pcvm); }
and view takes in typed model, , don't have rely on viewdata
, thing.
note: haven't compiled this, written it. there compilation bugs.
Comments
Post a Comment