asp.net mvc - MVC Viewmodel to display only model data -
this question similar link: viewmodel display partial information
i hoping example however. i've created model, looks this:
using system; using system.collections.generic; using system.componentmodel.dataannotations; namespace guestlisttemplate.models { public class guest { public int id { get; set; } [required] [display(name = "first name:")] public string firstname { get; set; } [display(name = "last name:")] public string lastname { get; set; } [datatype(datatype.emailaddress)] [display(name = "e-mail:")] public string email { get; set; } [datatype(datatype.phonenumber)] [display(name = "phone #:")] public string phone { get; set; } public boolean optin { get; set; } [display(name = "guest last name:")] public string guestlastname { get; set; } [display(name = "guest first name:")] public string guestfirstname { get; set; } [datatype(datatype.currency)] public decimal donation { get; set; } public int? attended { get; set; } } }
all of information not neccesary views. want make viewmodel display first name, last name, donation , perhaps join first , last name. trying doesn't work:
namespace guestlisttemplate.modelviewmodels { public class guestviewmodel { public string firstname { get; set; } public string lastname { get; set; } public decimal donation {get; set;} [display(name = "full name")] public string fullname { { return firstname + " " + lastname;} } } }
how tell mvc use guest model source of data viewmodel, or how bind them together? (the purpose thought might performance of application, performance??). understand how use viewmodels display data multiple tables , pull in data in case want pull data 1 table. last, better accomplished in controller?
i hope question makes sense. better use linq query such
var guests = db.guest.include(g => g.firstname, g.lastname, g.donation); return (guests.tolist());
(i understand above command might not exact syntax bbut idea). if better way can demonstrate basic way of doing entire viewmodel code. pretty linq, if offers basic example should able make work purposes.
edit:
this worked me (as interfaces outlined in answer below):
viewmodel same above.
here in controller:
var viewmodel = db.guests.select(g => new guestlistindexdata { id = g.id, firstname = g.firstname, lastname = g.lastname, donation = g.donation, attended = g.attended }).orderby(g => g.firstname); return view(viewmodel.tolist());
my view same listed above well. works, i'm not sure how faster performance getting out of won't use until working large databases.
i able achieve interfaces, such this:
public interface inameentity { string firstname { get; set; } string lastname { get; set; } }
and add guest:
public class guest : inameentity
and use inameentity in partial:
@model inameentity @html.textboxfor(i => i.firstname)
this technique use , works great if guest direct model in parent view. if there parent model class, it's doable little more complex setup.
Comments
Post a Comment