0

I'm trying to make some fields editable and some fields read-only based on user permissions (MVC version 5.2.3). I can see a whole bunch of answers on this subject for the @html.EditorFor(), but not plain old @html.Editor(). I've tried the following, none of which have yielded read-only fields:

@Html.Editor(property.Name, new { @disabled = "true" })
@Html.Editor(property.Name, new { @disabled = "disabled" })

Can anyone help me? Thanks very much.

KirstieBallance
  • 1,238
  • 12
  • 26
  • 1
    check this https://stackoverflow.com/questions/10109185/mvc3-editorfor-readonly – Tonmoy Saha Jul 25 '18 at 04:18
  • `@Html.Editor("Name", new { htmlAttributes = new { disabled = "disabled" } })` - but disabled controls do not post back a value, so its should be `@readonly = "readonly" `, but even that is not good practice if your binding to a data models in the POST method since a malicious user can still alter the value –  Jul 25 '18 at 08:44
  • Thanks @TonmoySaha I went with one of the answers in the link you provided. Specifically: @Html.Hidden(property.Name) @Html.Display(property.Name) in place of what would be the disabled/readonly html.Editor() – KirstieBallance Jul 25 '18 at 15:16

2 Answers2

0

You can write your own extension to receive your boolean property "disabled" as a parameter :

public static class HtmlExtensions
{
   public static MvcHtmlString EditorDisabled<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, bool disabled, object htmlAttributes = null)
  {
    return EditorDisabled(htmlHelper, expression, disabled, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));
  }

  public static MvcHtmlString EditorDisabled<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, bool disabled, IDictionary<string, object> htmlAttributes)
  {
    if (htmlAttributes == null)
    htmlAttributes = new Dictionary<string, object>();
    if (disabled)
    htmlAttributes["disabled"] = "disabled";
    return htmlHelper.Editor(expression, htmlAttributes);
  }
}
Mohammad
  • 1,549
  • 1
  • 15
  • 27
0

You could just change it from Editor to:

@Html.DisplayFor(model => model.Title)

And it will just pull the value from your model. From there you will just need to implement logic in razor regarding who can see what. EX:

if(Request.IsAuthenticated){
    if (isAdmin){
                @Html.Editor(model => model.Title)
                }
    if (isUser){
                @Html.DisplayFor(model => model.Title)
                }  
   }

I hope this helps put you on the right path!

DarthTommy
  • 419
  • 2
  • 10
  • I did that at first, and ended up nulling out all of the fields that were display only. That's why I have opted to add the @html.Hidden() portion to the if (isUser) block. – KirstieBallance Jul 25 '18 at 21:29