Disable DropDownList in View

1

Class

public class ConfiguracaoEstado
{
  ....

  [Required(ErrorMessage = "Selecione ao menos um estado.")]
  [Display(Name = "Estado")]
  public int EstadoID { get; set; }

  ...
}

Controller

private void createViewBag(ConfiguracaoEstado configuracaoestado)
{
  ViewBag.EstadoID = new SelectList(db.Estado, "Id", "uf", configuracaoestado.EstadoID);
  ....
}

View

<div class="form-group">
  @Html.LabelFor(model => model.EstadoID, "Estado", new { @class = "control-label col-md-2" })
  <div class="col-md-10">
           @Html.DropDownList("EstadoID", String.Empty);
           @Html.ValidationMessageFor(model => model.EstadoID)
  </div>
</div>

I would like that when running ActionResult Edit(int? id) DropDownList was disabled.

I tried this way:

@Html.DropDownList("EstadoID", String.Empty, new { disabled =  Model != null});

and did not work.

So I tried this way:

@Html.DropDownListFor(model => model.EstadoID,
                       (SelectList)ViewBag.EstadoID,
                       String.Empty, new {disabled = Model != null}
                     )

Then the following happens:

  • Disables control, but does not display contents of DropDownList .
  • If you remove String.Empty , it displays the contents, but not the contents, but the first one in the table.
  • With bringing the correct contents of DropDownList and disabling it?

        
    asked by anonymous 10.02.2015 / 16:47

    2 answers

    1

    At the top of your View, you can do the following:

    @{
        ddlProps = new { } as object;
        if (Model != null)
        {
            ddlProps = new { @readonly = "readonly", @disabled = "disabled"};
        }
    }
    

    Then doing the following in Helper overwrites the method.

    @Html.DropDownList("EstadoID", String.Empty)
    

    So:

    @Html.DropDownList("EstadoID", null,String.Empty,ddlProps);
    

    Just one tip in implementing your Controller: Use a Bind to remove ActionID from your control, just for security.

    public ActionResult MyAction([Bind(Exclude = "EstadoID")]MyObject model)
    
        
    10.02.2015 / 16:51
    1

    You can use JQuery.

       $(document).ready(function() {
             $("#EstadoID").prop("disabled", true);   
       });
    
       ... 
    
       @Html.DropDownListFor(model => model.EstadoID, (SelectList)ViewBag.EstadoID)
    
       ...
    

    Or

      $(document).ready(function() {
              $("#EstadoID").attr('disabled','disabled');  
        });
    
       ... 
    
       @Html.DropDownListFor(model => model.EstadoID, (SelectList)ViewBag.EstadoID)
    
       ...
    

    If you're interested, the link below has another way of rendering a dropdownlist

    How popular DropDownListFor with information of a foreign key?

        
    10.02.2015 / 17:44