I have a partial view that sometimes needs to collect data and sometimes just needs to display the saved data and not allow editing.
I would like to use the same partial view for both needs because the formatting is complex. However, I don’t want to just apply the “disabled” tag to specific controls: I want (on the server side) to render the read-only data as text, not as controls, so that it can’t be posted back.
(To complicate things, there is one field, for comments, that can be edited even when all the other fields are read-only, so there will be a post back.)
I’m thinking about a general solution to this problem. The simplest thing to do would be to apply the following code pattern to all the fields:
@{ if(condition) {
@Html.TextBoxFor(model=>model.Field)
}
else
{
@Html.DisplayFor(model=>model.Field)
}
}
But that’s inelegant and can lead to harder to read code. Also, since the pattern has to be manually applied, it would be easy to make mistakes.
I was toying with writing some extension methods to supplement TextBoxFor, et al, that would take an additional parameter that indicated whether to invoke TextBoxFor or DisplayFor.
But what I’d like even better would be something that I could set on a containing element that would automatically affect how the child elements are rendered, the way you can set the Visible property on an ASP.NET WebForms Panel control.
So now I’m treading out into the field of the hypothetical. To achieve such a thing, I would need a server-side containing element (perhaps following the same pattern as BeginForm) that had awareness of its own scope and could affect how the rendering extension calls it contained were invoked.
Is such a thing even possible?
I would look at this post: http://kazimanzurrashid.com/posts/asp-dot-net-mvc-viewmodel-usage-and-pick-your-best-pattern
It has an approach that remove logic, procedural code from Views and promotes better OOP and encapsulation. You may find it useful, at least informative.