开发者

ASP.NET MVC - ViewModels For Edit

Is it generally a good practice to have both view and edit models for an MVC app? Meaning, I wouldn't want validation attributes on a view model since it's basically read-开发者_如何学JAVAonly.


I generally create a new view model for each view. I find that the reuse in practice of ViewModels is just very low and trying to make them super generic doesn't work great and leads to some weird cases.

When I first started creating ViewModels I'd create these really abstract ViewModels that I'd try to enforce a bunch of business logic into but then I realized that in most cases the data I was trying to show in each case was totally different and reuse wasn't working. So I just started breaking my ViewModels into really tiny pieces that are used once. So far this has worked well.

Most of my business logic I now try to keep in the model instead of the view model. I my case my model is a entity framework model and I put the business logic in partial classes hanging off of my DB objects.


If your views are CRUD views, using the same view model makes sense. On the read only view, validation attributes would be ignored since you're not inputting a form. Once you get away from CRUD you have a lot more variations in how to structure your VMs. I have some situations where a field can only be set during insert. In this case I use the same VM for rendering the add, readonly and update screens (with DisplayFor vs InputFor in the view html itself), but I have different input models on my Insert and Update action methods.


You can have a property called ReadOnly (boolean) in your ViewModel. Based on that property appropriate view can be rendered.


You can use your model for editing purposes. You bind editable attributes to the View and other remain same even somebody was to fake inputs.

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

This makes sure you just get the First and Last named fields.

Maybe you missed it but don't display editable inputs for non-editable model attributes.


I think you are misunderstanding the purpose of separating the View and the Model in the Model View Control Pattern.

The View is about defining how the user will see the data i.e. what the web page will look like.

The Model defines that data that will be used i.e. the content that the view will display.

If you decide that you need two different web pages for viewing data and editing data then it would fit the MVC pattern that these two pages should have separate models and views.

But I'm generally against separating viewing and editing data into two web pages. With ajax today I would just do it in one web page.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜