views:

54

answers:

1

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??

A: 

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.

Jarrett Meyer
right but I want one view with many viewmodels. And a way to do it intelligently. otherwise it handcrafting many views. can not only creating a view model but a view for it. they are too tightly coupled. I want my view to be shaped by the viewmodel and depended on it. and certaintly not the reverse
Joe
@Joe, see edited answer
Jarrett Meyer
Yeah I was thinking about it some more. Perhaps I could a) create roles that I wont decorate on controller functionsb) put those roles in attributes on the views c) the helpers check current role and if dont match then output nothing and clear field of informationthose attributes on the fields in the viewmodel would be[CanViewOnly(Roles="aRole")][NoView(Roles="anotherRole")]
Joe