c# - When should I use ViewBag/model? -


i think using viewbag faster model.

my example is:

in action:

public actionresult myaction() {    viewbag.data = (from m in mydatabase.mytable select m).tolist(); } 

in view:

@foreach(var item in viewbag.data) {    <tr>       <td>@item.mycolumn</td>    </tr> } 

by using model:

[table("tbl_mytable")] public class mytable() {    public int id { get; set; }    public int column2 { get; set; }    public int column3 { get; set; }    // ...    public ienumerable<mytable> data { get; set; } } 

in model:

public class mainclass {    public list<mytable> mymethod()    {       list<mytable> list = new list<mytable>();       // code logic find data in database , add list       list.add(new mytable       {          column2 = ...          column3 = ...       });       return list;    } } 

in action:

public actionresult myaction() {    mainclass mc = new mainclass();    mytable model = new mytable();    model.data = mc.mymethod();    return view(model); } 

in view:

@using myprojectname.models @model myprojectname.models.mytable  @foreach(mytable item in model.data) {    <tr>       <td>@item.column1</td>    </tr> } 

both of them working, , viewbag easier model.

so, can tell me: when should use viewbag/model?

viewbag not faster. in both cases creating model of list<mytable>. code have show creating 'mytable' model pointless - creating new collection containing duplicates existing collection. in controller needs be

public actionresult myaction() {   var model = (from m in mydatabase.mytable select m).tolist();   return view(model); } 

and in view

@model list<myprojectname.models.mytable> // using statement not required when use qualified name @foreach(var item in model) {   <tr>     <td>@item.mycolumn</td>   </tr> } 

and mytable model should not have property public ienumerable<mytable> data { get; set; } unless creating hierarchical model.

always use models (preferably view model) in view can take advantage of strong typing (vs viewbag dynamic)


Comments

Popular posts from this blog

facebook - android ACTION_SEND to share with specific application only -

python - Creating a new virtualenv gives a permissions error -

javascript - cocos2d-js draw circle not instantly -