2012-05-23 98 views
3

我想使用DropDownList幫助器在ASP.NET MVC 4應用程序中使用selectedvalue構建選擇列表,但是當生成下拉列表時,沒有任何選定的值,即使作爲源給出的SelectList具有SelectedValue集合。ASP.NET MVC 4 DropDownList SelectedValue不起作用

下面的代碼:

我的模型:

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; 
     } 
    } 
} 

我的控制器:

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" 
      }; 
     } 
    } 
} 

筆者認爲:

<h2>View1</h2> 

@Html.DropDownList("teste", ViewBag.ListaContas as SelectList) 

下拉建有四個選項Contas()m方法創建,但沒有一個被選中。會是什麼呢?

回答

5

您應該將3作爲SelectList構造函數的最後一個參數傳入,而不是一個對象。

此外,您的GetHashCode函數是半分裂的(提示:13 * 7是一個常量)。

+0

Ooops,我沒有真正完成課程,我會檢查GetHashCode。 =) – Alaor

+0

順便說一句,它解決了這個問題。非常感謝。 – Alaor