c# - MVC 4 how pass data correctly from controller to view -
i have controller linq statement passing data view. trying find more efficient , better coding method this. home controller statement follows.
var melt furnace1 = (from item in db.tbl_dppithr item.productionhour >= startshift && item.productionhour <= enddate select item).sum(x => x.furnace1total), viewdata["furnace1total"] = melt.furnace1;
in view reference viewdata show this. using
@model dynamic
now have quite alot of linq statements inside index method. , each 1 doing viewdata[]
i hoping can show how pass more 1 var controller across view without viewdata or viewbag methods. , how access within view.
you should create viewmodel
of data needed , pass down view.
public class viewmodel { public list<int> melt1 { get; set; } public void loadmeltproperties() { if (melt1 == null) { melt1 = new list<int>(); } melt1 = (from item in db.tbl_dppithr item.productionhour >= startshift && item.productionhour <= enddate select item).sum(x => x.furnace1total).tolist(); } public viewmodel load() { loadmeltproperties(); return this; } } public actionresult yourcontrolleraction() { var vm = new viewmodel().load(); return view("viewname", vm); }
then in view can use strongly typed
model rather dynamic
@model viewmodel
you can iterate on viewmodel properties via:
foreach(var melt in model.melt1) { // require }
Comments
Post a Comment