[RESOLVED]How to prevent change property some roles?

Hi.

There are
two roles (Administrator, User). User roles need to disable edit certain properties.
Please share your experience as someone solves this problem.

Model

public class MyModel
    {
        public int Id { get; set; }

        public string Name { get; set; }

        //This property should only edit the administrators
        public bool Enabled { get; set; }

    }

@model Appointment.Models.MyModel @using (Html.BeginForm()) { @Html.AntiForgeryToken() <div class="form-horizontal"> @Html.ValidationSummary(true, "", new { @class = "text-danger" }) <div class="form-group"> @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } }) </div> </div> <div class="form-group"> @Html.LabelFor(m => m.Enabled, new { @class = "col-md-2 control-label" }) <div class="col-md-10"> @Html.CheckBoxFor(m => m.Enabled, new { @class = "form-control" }) </div> </div> <div class="form-group"> <div class="col-md-offset-2 col-md-10"> <input type="submit" value="Save" class="btn btn-default" /> </div> </div> </div> }

Property "Enabled" should be available only to administrators in View

I would be grateful
for any advice!

up

Hi DSerg,

For this requirement, you just need to base on current user’s role to add that field.

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })

        <div class="form-group">
            @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
            </div>
        </div>
       @if(User.IsInRole("Administrator"))
         {
        <div class="form-group">
            @Html.LabelFor(m => m.Enabled, new { @class = "col-md-2 control-label" })
            <div class="col-md-10">
                @Html.CheckBoxFor(m => m.Enabled, new { @class = "form-control" })
            </div>
        </div>
        }
        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Save" class="btn btn-default" />
            </div>
        </div>
    </div>
}

Best Regards

Starain

Leave a Reply