I am not able to make the value of a property be selected using the Razor Helper DropDownListFor

4

In my ASP.NET MVC 5 application I'm using .Net 4.5 I'm not able to make the option selected for a given property.

Example of my class:

public class Funcionario
{
    [Required(ErrorMessage = "O campo {0} é necessário")]
    [StringLength(150, MinimumLength = 3, ErrorMessage = "O campo {0} aceita somente entre {2} e {1}")]
    public string Nome { get; set; }

    [DefaultValue(false)]
    [Required(ErrorMessage = "O campo {0} é necessário")]
    public bool Ativo { get; set; }

    [DefaultValue("F")]
    [Required(ErrorMessage = "O campo {0} é necessário")]
    public string Sexo { get; set; }

    [DisplayName("Cargo")]
    [DefaultValue(null)]
    public int? CargoId { get; set; }
}

The code snippet from my view:

<div class="form-group">
    @Html.LabelFor(x => x.Nome, new { @class = "col-sm-2 control-label" })
    <div class="col-sm-7">
        @Html.TextBoxFor(x => x.Nome, new { @class = "form-control", placeholder = "Nome", autofocus = "autofocus" })
        @Html.ValidationMessageFor(x => x.Nome)
    </div>

    @Html.LabelFor(x => x.Ativo, new { @class = "col-sm-1 control-label" })
    <div class="col-sm-2">
        @Html.DropDownListFor(x => x.Ativo, ViewBag.Ativo as SelectList, new { @class = "form-control" })
        @Html.ValidationMessageFor(x => x.Ativo)
    </div>
</div>

<div class="form-group">
    @Html.LabelFor(x => x.Sexo, new { @class = "col-sm-2 control-label" })
    <div class="col-sm-2">
        @Html.DropDownListFor(x => x.Sexo, ViewBag.Sexo as SelectList, new { @class = "form-control" })
        @Html.ValidationMessageFor(x => x.Sexo)
    </div>

    @Html.LabelFor(x => x.CargoId, new { @class = "col-sm-1 control-label" })
    <div class="col-sm-7">
        @Html.DropDownListFor(x => x.CargoId, ViewBag.Cargos as SelectList, new { @class = "form-control" })
        @Html.ValidationMessageFor(x => x.CargoId)
    </div>
</div>

How to return the view to the Controller and how to hedge the values in the ViewBag:

public ActionResult Alterar(int id)
{
    var obj = repository.Funcionarios.SingleOrDefault(x=>x.EmpresaId == SessionEmpresaId && x.Id == id)
    if (obj == null)
        return HttpNotFound();
    SetarValoresDeCadastroNaViewBag();
    return View("Cadastro", obj);
}
...
private void SetarValoresDeCadastroNaViewBag()
{
    var AtivoList = new List<dynamic>();
    AtivoList.Add(new { Id = "", Text = "" });
    AtivoList.Add(new { Id = true.ToString(), Text = "SIM" });
    AtivoList.Add(new { Id = false.ToString(), Text = "NÃO" });
    ViewBag.Ativo = new SelectList(AtivoList, "Id", "Text");

    var SexoList = new List<dynamic>();
    SexoList.Add(new { Id = "", Text = "" });
    SexoList.Add(new { Id = "M", Text = "Masculino" });
    SexoList.Add(new { Id = "F", Text = "Feminino" });
    ViewBag.Sexo = new SelectList(SexoList, "Id", "Text");

    var cargos = repository.Cargos.Where(x => x.EmpresaId == SessopmEmpresaId).Select(x => new
    {
        Id = x.Id,
        Descricao = x.Descricao
    }).ToList<dynamic>();
    cargos.Insert(0, new { Id = "", Descricao = "" });
    ViewBag.Cargos = new SelectList(cargos, "Id", "Descricao");
}

Finally, note that the job is loaded, but the gender and asset does not:

BydebuggingIhaveseenthatthefieldsarepopulatedfortheview.Ialsosawthatthetagsaregeneratedcorrectlyinthepagehtml.

<divclass="form-group">
    <label class="col-sm-2 control-label" for="Nome">Nome</label>
    <div class="col-sm-7">
        <input autofocus="autofocus" class="form-control input-sm" id="Nome" name="Nome" placeholder="Nome" type="text" value="Fulano de Tal">
    </div>
    <label class="col-sm-1 control-label" for="Ativo">Ativo</label>
    <div class="col-sm-2">
        <select class="form-control input-sm" id="Ativo" name="Ativo">
            <option value=""></option>
            <option value="True">SIM</option>
            <option value="False">NÃO</option>
        </select>
    </div>
</div>
<div class="form-group">
    <label class="col-sm-2 control-label" for="Sexo">Sexo</label>
    <div class="col-sm-2">
        <select class="form-control input-sm" id="Sexo" name="Sexo">
            <option value=""></option>
            <option value="M">Masculino</option>
            <option value="F">Feminino</option>
        </select>
    </div>
    <label class="col-sm-1 control-label" for="CargoId">Cargo</label>
    <div class="col-sm-7">
        <select class="form-control input-sm" id="CargoId" name="CargoId">
            <option value=""></option>
            <option value="1">...</option>
            <option selected="selected" value="11">Assistente Social</option>
        </select>
    </div>
</div>

So, please, how can I resolve this?

    
asked by anonymous 05.03.2014 / 18:39

1 answer

2

I can not explain why this happens (some bug in MVC) but the field name in ViewBag is conflicting with your Model

This excerpt, for example:

ViewBag.Sexo = new SelectList(SexoList, "Id", "Text");

Change the name of the ViewBag field to ViewBag.SexoList , or any value that does not conflict with Model.Sexo

ViewBag.SexoList = new SelectList(SexoList, "Id", "Text");

And here:

@Html.LabelFor(x => x.Sexo, new { @class = "col-sm-2 control-label" })
<div class="col-sm-2">
    @Html.DropDownListFor(x => x.Sexo, ViewBag.SexoList as SelectList, new { @class = "form-control" })
    @Html.ValidationMessageFor(x => x.Sexo)
</div>
    
05.03.2014 / 19:38