Oniel
Oniel

Reputation: 13

MVC3 editor template for multiple types

I have a model with some parameters that a User should be able to see but not edit and others they should be able to edit. The same is true of the Author. So, I used [UIHint("Author")] and [UIHint("User")] attributes and wrote a couple editor templates, like so:

@inherits System.Web.Mvc.WebViewPage

@if (ViewBag.RoleId > (int)Role.RoleEnum.Author)
{
    @Html.TextBoxFor(m => m, new { disabled = "disabled" })
}
else
{
    @Html.TextBoxFor(m => m)
}

This almost does what I want. I'd like to be able to apply these attributes to booleans and get check boxes - like the default EditorFor. I suppose I could make another template and use something like [UIHint("AuthorBool")], but I'm hoping to come up with something better.

Upvotes: 0

Views: 783

Answers (1)

Dan B
Dan B

Reputation: 936

Hi Oniel,

You could create separate ViewModels for each type of user and use the data annotation of [ReadOnly]. But then you get into the realms of large amounts of repetition.

Personally I would recommend that you create your own version of each data type and implement standard role based handling using additionalmetadata data annotations to customise. Okay bit of work to begin with but then massively re-usable and highly portable.

Example:

[UIHint("MyCustomTemplateControl")]
[AdditionalMetadata("DenyEditUnlessInRole", "Admin")] 
public string MyName { get; set; }

or:

[UIHint("MyCustomTemplateControl")]
[AdditionalMetadata("DenyEditIfInRole", "StandardUser")] 
public string MyName { get; set; }

You can perform a code based / database based lookup in a class somewhere else that your datatypes templates query to make a decision on whether a user/role should get read/edit access to this property.

Does this make sense?

As a third option, create an editortemplate for the entire object and only include those fields and field types you are interesting in exposing.

MVC is so flexible - I suppose in the end it depends on how DRY do you want to make your code.

Good luck! Dan.

Upvotes: 1

Related Questions