Search code examples
asp.net-mvcrazorviewbag

MVC.ViewBag is wrong?


I'm using

ViewBag.Something = session.Query<Something>().ToList();

To pass information from class Something to View and use it in selectList

@Html.DropDownListFor(model => model.model, new SelectList(ViewBag.Something, "Id", "name"), "--Smthing--")

Is that bad? and how can i change it to be better?


Solution

  • The practice is not at all bad but it is recommonded to have a List property in our mode it self. in your case something like

    public ActinResult YourActionMethod()
    {
        YourModelObject.Something = session.Query<Something>().ToList();
        // And return your view after further code statements
        return View(YourModelObject);
    }
    

    Infact instead of the original list object you cancreate a SelectList object where you can easily bind key and value and send it to view. By this way you can add all your business and build your model at once place and can populate it from the location you want to. Later View will just use that model rather than applying some more intelligence to it. It helps alot as all your values resides under same object rather than some in Model and some in ViewBag.

    Secondly this practice is also fine if you don't have this list at more than one place and you are not reusing this model in any views. Also if you want to access this property outside your view e.g. in Layout or in some parent view which is consuming your view.

    You can take a look at following post which explains how to bind a list to your model.

    Setting default selected value of selectlist inside an editor template