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 つのオプションで作成されますが、どれも選択されていません。どうなり得るか?

4

1 に答える 1

5

3オブジェクトではなく、最後のパラメーターとして SelectList コンストラクターに渡す必要があります。

また、GetHashCode関数は半分壊れています (ヒント: 13*7 は定数です)。

于 2012-05-23T00:55:17.057 に答える