繁体   English   中英

ASP.NET MVC 4 DropDownList SelectedValue不起作用

[英]ASP.NET MVC 4 DropDownList SelectedValue doesn't work

我正在尝试使用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()方法创建的四个选项构建下拉列表,但不选择任何选项。 会是什么呢?

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM