Search code examples
c#asp.netasp.net-mvcrazor

Set Dropdownlist Selected Value in the View


I need to set the setectedValue of a DropDownList using razor, but because it's a list used several times in the same page, I can't set the selected value in the Controller, so how can I set it in the View?

Actual Controller List code:

ViewBag.CargaTipos = new SelectList(db.CargaTipos, "Id", "Nome").OrderBy(c => c.Text);

Actual View:

@Html.DropDownListFor(modelItem => item.CargaTipo.Id, (IEnumerable<SelectListItem>)ViewBag.CargaTipos)

Models:

[Table("Cargas")]
public class Carga
{
    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    [Required]
    [ForeignKey("CargaTipo")]
    public int CargaTipo_Id { get; set; }

    [Display(Name = "Tipo de Carga")]
    public virtual CargaTipo CargaTipo { get; set; }
}

[Table("CargaTipos")]
public partial class CargaTipo
{
    public CargaTipo()
    {
        this.Cargas = new HashSet<Carga>();
    }

    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }
    public string Nome { get; set; }

    public virtual ICollection<Carga> Cargas { get; set; }
}

Solution

  • Cannot set SelectedValue property outside constructor of SelectedList class. Use this instead

    ViewBag.CargaTipos = db.CargaTipos;
    

    View

    @Html.DropDownListFor(modelItem => item.CargaTipo.Id,new SelectList(ViewBag.CargaTipos,"Id","Nome",YOUR_SELECTED_VALUE))