Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set disabled in MVC htmlAttribute

Tags:

c#

asp.net-mvc

When using an HTML Helper, what is the best method to set an attribute based on a condition. For example

<%if (Page.User.IsInRole("administrator")) {%>
<%=Html.TextBoxFor(m => m.FirstName, new {@class='contactDetails'}%>
<%} else {%>
<%=Html.TextBoxFor(m => m.FirstName, new {@class='contactDetails', disabled = true}%>
<%}%>

There must be a better way to programmatically add just one additional KeyPair to the anonymous type? Can't use

new { .... disabled = Page.User.IsInRole("administrator") ... }

as the browser takes any disabled attribute value as making the input disabled

like image 214
Ollie Avatar asked Mar 23 '10 12:03

Ollie


People also ask

How disable HTML Textboxfor in MVC?

You can make the input 'read only' by using 'readonly'. This will let the data be POSTED back, but the user cannot edit the information in the traditional fashion. Keep in mind that people can use a tool like Firebug or Dragonfly to edit the data and post it back.


2 Answers

I could suggest you to use mvccontrib.FluentHtml.

You can do something like this

 <%=this.TextBox(m=>m.FirstNam ).Disabled(Page.User.IsInRole("administrator"))%>
like image 129
Dennis C Avatar answered Sep 28 '22 07:09

Dennis C


It works for me as well...

<%: Html.DropDownList("SportID", (SelectList)ViewData["SportsSelectList"], "-- Select --", new { @disabled = "disabled", @readonly = "readonly" })%>

<%= Html.CheckBoxFor(model => model.IsActive, new { @disabled = "disabled", @readonly = "readonly" })%>
like image 24
Friend Avatar answered Sep 28 '22 07:09

Friend