0

The code in View,

@{
    var MyModel = Entity.Employees.Select(t=> 
       new {t.FullName, t.Department.DepartmentName}));
}

@foreach (var e  in MyModel ) {
     <div> Name: @e.FullName  - @e.DepartmentName </div>
}

Controller is empty

public ActionResult Index()
{
  return View();
}

I am new to Asp.net MVC. Here is something I learned from book.

  1. Controller retrieves Model data, pass it to View
  2. View consumes Model data
  3. Use Strongly-typed model whenever possible

In controller, when model data is from EF/LinQ query, the type is often anonymous, not strongly-typed when passing to view. On the other side, I want to avoid generating one-time-used strongly-typed model.

Above code retrieves model data from View, it's anonymous-but-strongly-typed. seems I can get benefits from both side.

My question is: Should I populate model data from a view? If No, Why?

I found this helpful: it passes dynamic data between controller and view, it's fluent, but not strongly-typed

Community
  • 1
  • 1
Rm558
  • 4,621
  • 3
  • 38
  • 43

3 Answers3

1

No, you should not.

You can read any of the articles online that tell you why MVC is a good pattern. You'll find that you have more opportunities for code reuse, unit-testability, etc.

If you're not using the controller to pass a view model to the view, then you're not really following MVC. You might as well be using Razor Web Pages.

StriplingWarrior
  • 151,543
  • 27
  • 246
  • 315
0

Think of Skinny Controllers, Fat Models and Dumb Views.

Views should contain as little logic as possible. As the view model is created specifically for a view, the only responsibility of the view is to render itself using the view model's data that was created in the controller. If there are a lot of decisions, conversions or other logic in your view, then you are not really using the MVC pattern properly.

So as to your question: create your model in the controller, not in the view.

L-Four
  • 13,345
  • 9
  • 65
  • 109
-1

Thanks for all the good answers, they are right.

But my recent experience tends to say Yes... Only In Certain Case,

My project has a number of grid pages. The sole purpose is displaying some grid data. it is often

  1. Not reused elsewhere.
  2. Not needed a Unit Test.
  3. Often asked to add/delete/change columns

Unit Test -- the Grid data is directly from an entity framework, basically a SQL query, There is no need to unit test a SQL query. (a stored procedure may need).

Change Handling -- it literally takes minutes to make an entity query change, bind to an column, right click the cshtml file & publish to production, all in one file. Asp.net will dynamically compile it.

Performance -- the project is a line of business application. Application performance has not been an issue, whereas programmer's productivity is importance, this approach does not lose any strongly-typed checking, auto-completion, etc.

Rm558
  • 4,621
  • 3
  • 38
  • 43