I am unable to make the value of a property selected using the Razor Helper Dropdownlistfor

Asked

Viewed 1,871 times

4

Dear Ones, in my ASP.NET MVC 5 application I am using . Net 4.5 I am unable to make the option to be selected for a certain 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 to view by Controller and how to select values in 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, see that the position is charged, but the sex and active not:

Exemplo da página renderizada

Debugging I saw that the fields go filled for the view. I also saw that the tags are correctly generated in the html of the page.

<div class="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 fix this?

  • Check in debug if your obj in action Alterar contains the expected value, ex. obj.Sexo = "M";

  • Yes, I had checked and is.

  • I suggest another test to try debugging the problem, include in the view something visible to list the contents of the field: @Model.Sexo

  • I tested, the values are printed correctly. For some reason when removing the addition of the blank record, //SexoList.Add(new { Id = "", Text = "" });, value is now selected.

  • As these are two required fields I will remove this line that adds the blank record. But you know why this and how it could be done to keep the <option> blank without gambiarras?

  • Look at the answer I posted, so it should work.

Show 1 more comment

1 answer

2


I can’t explain why this happened (some bug in MVC) but the name of the field in ViewBag is conflicting with your Model

This passage for example:

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

Change the Viewbag field name 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>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.