I have an asp.net mvc 2 app. I need to display the same page to each user. But each user has different rights to the data. IE some can see but not edit some data, some cannot edit nor see the data. Ideally data that cannot be seen nor edited is whitespace on the view. For security reasons I want my viewmodels to be sparse as possible. By that I mean if a field cannot be seen nor edited , that field should not be on the viewmodel. Obviously I can write view for each view model but that seems wasteful. So here is my idea/wishlist
Can I decorate the viewmodel with attributes and hook into a pre render event of the html helpers and tell it to do
instead???
Can I have the html helpers output
for entries not found on the viewmodel??
or
can I easily convert a view built into code then programaticlly build the markup and then put into the render engine to be processed and viewd as html on client side??
The way you've phrased the question, I'm afraid any answer would result in a quite complex view. Deciding which view to display (and which view model to build) dependent on roles of the user is the responsibility of the controller.
EDIT 1: Response to comment
Could you do something like this?
<% if (Model.AllowEdit) { %>
<%= Html.TextBoxFor(x => x.SomeProperty); %>
<% } else if (Model.AllowView) { %>
<%= Html.Encode(Model.SomeProperty) %>
<% } else { %>
<span>You may not view this property.</span>
<% } %>
This could translate into a helper control.
public static ExtensionsOfHtmlHelper
{
public static MvcHtmlString DynamicTextBox(this HtmlHelper html, Func<TModel, object> lambda, bool edit, bool view)
{
if (edit)
{
return html.TextBoxFor(lambda);
}
else if (view)
{
return html.LabelFor(lambda);
}
else
{
return MvcHtmlString.Create("<span>You may not view this value.</span>");
}
}
}
Then, in your view,
<%= Html.DynamicTextBox(x => x.SomeProperty, Model.AllowEdit, Model.AllowView) %>
Something close-ish to that should work.