ASP.NET MVC - ViewModels For Edit

As a rule, is it good practice to view and edit models for an MVC application? So I don’t need the validation attributes on the view model, since they are mostly read-only.

+6
asp.net-mvc
source share
5 answers

I usually create a new view model for each view. I find that reusing ViewModels in practice is very low, and trying to make them super-versatile doesn't work perfectly and leads to some strange cases.

When I first started creating ViewModels, I would create these really abstract ViewModels models that I would try to use a bunch of business logic in, but then I realized that in most cases the data that I tried to show in each case was completely different and reuse did not work. So I just started breaking my ViewModels into really tiny pieces that are used once. So far, it works well.

Most of my business logic is now trying to save a model, not a presentation model. In my case, my model is an entity structure model, and I put business logic in partial classes that depend on my database objects.

+2
source share

If your views are CRUD views, using the same presentation model makes sense. In the Read-Only view, validation attributes are ignored because you are not entering a form. Once you get rid of CRUD, you have many more options for structuring your virtual machines. I have situations where the field can only be set during insertion. In this case, I use the same virtual machine to display the add, read and update screens (with DisplayFor vs InputFor in the html view itself), but I have different input models in my "Insert" and "Update" action methods.

+1
source share

You may have the ReadOnly (boolean) property in your ViewModel. Based on this property, the corresponding view can be displayed.

0
source share

You can use your model for editing purposes. You bind editable attributes to the view, while others remain the same, even if someone has to fake the inputs.

public ActionResult Update([Bind(Include="First, Last")]User user) 

This ensures that you simply get the First and Last named fields.

You may have missed it, but you are not displaying editable inputs for non-editable model attributes.

0
source share

I think you don’t understand the purpose of separating View and model into a model representation control pattern.

The view indicates how the user sees the data, for example, how the web page will look.

The model determines what data will be used, i.e. content displayed in the view.

If you decide that you need two different web pages to view data and edit data, then it will follow the MVC pattern, that these two pages should have separate models and views.

But I am generally against splitting browsing and editing data into two web pages. With ajax today, I would just do it on one web page.

0
source share

All Articles