viewmodel - ASP.NET MVC - How exactly to use View Models -
let's have page allows editing of user's details, have viewmodel this:
public class userviewmodel { public string username { get; set; } public string password { get; set; } public int managerid { get; set; } public string category { get; set; } }
so on edituser action can have passed model binder , can map domain model:
public actionresult edituser(userviewmodel user) { ...
however, page displays form needs details such list of managers , categories provide dropdowns fields. might display list of other users in sidebar can switch between different users you're editing.
so have view model:
public class viewuserviewmodel { public userviewmodel editinguser { get; set; } public ienumerable<selectlistitem> managers { get; set; } public ienumerable<selectlistitem> categories { get; set; } public ienumerable<selectlistitem> allusers { get; set; } }
is correct way it? both view models? if so, there naming convention should use can distinguish between vms models , vms contain data page?
have got wrong?
how in shortcut:
- create separate viewmodel class each form on page, render these classes partialviews
@{html.renderpartial("partialname", model.partialmodel);}
. - if page contains things html metas make separated class metas , put in section on page.
- rest cases "should put in separated class?" judgement.
so example have page has kind of login/register bar or popup whatever.
public class somepageviewmodel { public registerbarvm register { get; set; } public loginbarvm loginbar { get; set; } public metasvm metas { get; set; } public string maybepagetitle { get; set;} public string maybepagecontent { get; set;} [hiddeninput(displayvalue = false)] public int idifneeded { get; set; } public ienumerable<selectlistitem> someitems {get; set;} public string pickeditemid { get;set; } } public class registerbarvm { public string registerusername {get;set;} public string registerpassword {get;set;} //... } public class loginbarvm { public string loginuserame {get;set;} public string loginpassword {get;set;} //... } //cshtml @model yourclassesnamespace.somepageviewmodel @{ html.renderpartial("loginbar", model.loginbar); //form inside html.renderpartial("registerbar", model.registerbar); //form inside using(html.beginform()) { @html.editorfor(m => m.idifneeded) @hmtl.editorfor(m => m.maybepagetitle) @hmtl.editorfor(m => m.maybepagecontent) @hmtl.dropdownlistfor(m => m.pickeditemid, new selectlist(model.someitems)) <input type="submit" value="update" /> } } @section metas { @{html.renderpartial("meatas", model.metas} }
about editor templates brad wilsons blog , google or stacks resources display/editor templates , htmlhelpers. useful building consistent websites.
Comments
Post a Comment