ASP.NET MVC 4 DropDownList SelectedValue不起作用

时间:2012-05-23 00:11:35

标签: c# asp.net razor asp.net-mvc-4

我正在尝试使用DropDownList帮助程序在ASP.NET MVC 4应用程序中构建具有selectedvalue的选择列表,但是当生成下拉列表时,它没有任何选定值,即使给出SelectList也是如此因为source设置了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()方法创建的四个选项构建下拉列表,但不选择任何选项。它可能是什么?

1 个答案:

答案 0 :(得分:5)

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

此外,您的GetHashCode函数已经半破(提示:13 * 7是常量)。