Travis J
Travis J

Reputation: 82297

How can I re-use the model type from a view in the view?

How can I reuse my declared model type? At the top of the view there is the declaration

@model mySpace.viewModels.viewModel

What I want to do is later on in the page, do something like

@for( viewModel vM in ViewBag.viewModels )
{
 //some foo bar
}

Upvotes: 0

Views: 88

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1039268

If you already have a strongly typed view, you really shouldn't be even thinking about ViewBag/ViewData. Once you have strongly typed view to a view model all you have to do in this view is use the properties of this view model, like so:

@foreach (viewModel vm in Model.SomeSubModels)
{
    //some foo bar
}

or even better, to avoid the horrible foreach loops in your views, you could use using editor templates (if you need to edit some properties):

@Html.EditorFor(x => x.SomeSubModels)

or using a display template (if you only want to display values of your view model properties to the user):

@Html.DisplayFor(x => x.SomeSubModels)

So here's are a couple of basic rules to follow when designing an ASP.NET MVC application (in that order):

  1. you forget about ViewBag/ViewData. It's as if they didn't exist. You simply wipe them out of existence. You will do a real service to yourself if you forget about them.
  2. you define a view model that is a class containing all the properties that your view will need.
  3. you have your controller action query your repositories and domain models and map the results to this view model that will be passed to the view.
  4. in the corresponding view you simply use the properties of the view model that the controller action provided to display some information.

Rule number 1. is the real basics and the most important one. If you don't respect this rule, you really aren't doing ASP.NET MVC correctly.

Upvotes: 3

Related Questions