user1826176
user1826176

Reputation: 309

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?

Upvotes: 1

Views: 2375

Answers (1)

janhartmann
janhartmann

Reputation: 15003

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?

Upvotes: 6

Related Questions