Search code examples
c#asp.net-mvcentity-frameworkmodel-view-controllerviewbag

Passing data to a view with MVC 6 EF


Since I've seen several people advising against using the ViewBag I was wondering how to do it correctly using:

return View()

I've read that you need to use so called ViewModels but those don't seem to apply when you are working with the Entity Framework.

How do I pass data to the View? How do I access said data within the View?


Solution

  • You can pass a "view model" or object like:

    public ActionResult Index() {
        var model = new MyViewModel();
        model.MyProperty = "My Property Value"; // Or fill the model out from your data store. E.g. by creating an object to return your view model: new CreateMyViewModel();
    
        return View(model);
    }
    

    In your view page (here Index.cshtml) add this in the top:

    @model MyViewModel
    

    And access the properties on MyViewModel like:

    @Model.MyProperty
    @Html.DisplayFor(model => model.MyProperty)
    

    For a more in-depth answer, take a look at: What is ViewModel in MVC?