1

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?

user1826176
  • 309
  • 2
  • 14
  • 1
    1) View models *very much* apply when working with Entity Framework. One of the most important reasons to use view models is because most validation and data you need in a view is totally inappropriate to exist on your entity class. 2) If you're struggling with something like this, you need to take more time to familiarize yourself with ASP.NET MVC. Go through the tutorials at http://www.asp.net/mvc. – Chris Pratt Feb 20 '15 at 14:03

1 Answers1

6

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?

Community
  • 1
  • 1
janhartmann
  • 14,713
  • 15
  • 82
  • 138