3

我正在尝试使用 DropDownList 帮助器在 ASP.NET MVC 4 应用程序中构建一个带有 selectedvalue 的选择列表,但是当生成下拉列表时,它没有任何选择的值,即使作为源给出的 SelectList 有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() 方法创建的四个选项构建的,但没有一个被选中。会是什么呢?

4

1 回答 1

5

您应该3作为最后一个参数传入 SelectList 构造函数,而不是对象。

此外,您的GetHashCode函数是半损坏的(提示:13*7 是一个常数)。

于 2012-05-23T00:55:17.057 回答