I’m trying to use the DropDownList helper to build a select list with a selectedvalue in an ASP.NET MVC 4 appliction, but when the dropdownlist is generated, it doesn’t have any selected value, even if the SelectList given as source have the SelectedValue set.
Here’s the code:
My model:
using System;
using System.Collections.Generic;
using System.Linq;
using System.ComponentModel.DataAnnotations;
namespace MvcApplication3.Models
{
public class Conta
{
public long ContaId { get; set; }
public string Nome { get; set; }
public DateTime DataInicial { get; set; }
public decimal SaldoInicial { get; set; }
public string Owner;
public override bool Equals(object obj)
{
if (obj == null)
return false;
if (obj.GetType() != typeof(Conta))
return false;
Conta conta = (Conta)obj;
if ((this.ContaId == conta.ContaId) && (this.Owner.Equals(conta.Owner)) && (this.Nome.Equals(conta.Nome)))
return true;
return false;
}
public override int GetHashCode()
{
int hash = 13;
hash = (hash * 7) + ContaId.GetHashCode();
return hash;
}
}
}
My Controller:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcApplication3.Models;
namespace MvcApplication3.Controllers
{
public class HomeController : Controller
{
public ActionResult View1()
{
Conta selecionada = new Conta()
{
ContaId = 3,
Nome = "Ourocard VISA",
Owner = "teste"
};
SelectList selectList = new SelectList(Contas(), "ContaId", "Nome", selecionada);
ViewBag.ListaContas = selectList;
return View();
}
IEnumerable<Conta> Contas()
{
yield return new Conta()
{
ContaId = 1,
Nome = "Banco do Brasil",
Owner = "teste"
};
yield return new Conta()
{
ContaId = 2,
Nome = "Caixa Econômica",
Owner = "teste"
};
yield return new Conta()
{
ContaId = 3,
Nome = "Ourocard VISA",
Owner = "teste"
};
yield return new Conta()
{
ContaId = 4,
Nome = "American Express",
Owner = "teste"
};
}
}
}
My View:
<h2>View1</h2>
@Html.DropDownList("teste", ViewBag.ListaContas as SelectList)
The dropdown is built with the four options that the Contas() method created, but none of them is selected. What could it be?
You should pass in
3as the last parameter to the SelectList constructor, instead of an object.Also, your
GetHashCodefunction is semi-broken (hint: 13*7 is a constant).