简体   繁体   中英

MVC 4 reuse views and view models best practice

I have 3 screens that share a section(with model data in it(@Html.TextBoxFor)). What is the best way to implement this screens?

What I tried:

1) Partial view for the common section(_ClientData). 3 views for the different screens. 3 view models that have common property(ClientData), that is the view model of the partial. Problem: If I pass the model to the partial as @{Html.RenderPartial("_ClientData", Model.ClientData);} the data from the partial is not submited to the model. If I pass the model to the partial as @{Html.RenderPartial("_ClientData", Model);} and reference the properties with a fill name the data is submited, but I can't pass models with different types to the partial view.

2) Use one big View model with all the data required by the 3 screens, one view and show/hide some elements depending on some flag. Problem: I can't use ValidationAttributes(for example if one field is required in screen 1, but it's not shown in screen 2 and its value is null, the validation will fire). I can use some manual validation in the controller but the whole thing with the all in one view and viewmodel sounds very bad.

Partials are usually not the best choice in case you want to place them inside one form and submit together. In such scenario it is better to take advantage of EditorTemplates which will solve your problem.

Firstly you would have to drag your partials to the folder ~/Shared/EditorTemplates/ and rename them to match the model name.

Then you can call them in your view like this:

Html.EditorFor(model => model.ClientData)

Thanks to this your HTML code (the name attributes to be precise) will be generated in such a way that your default model binder will be able to bind this part of your view as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM