如何解决此错误"IEnumerable< SelectListItem>"在下拉列表MVC中 [英] How can I resolve this error 'IEnumerable<SelectListItem>' in the drop down list MVC

查看:144
本文介绍了如何解决此错误"IEnumerable< SelectListItem>"在下拉列表MVC中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的MVC项目中,我将货币列表传递到下拉列表中的视图.但是,一旦尝试发布视图,就会出现以下异常:

In my MVC project I pass list of currencies to the view within the drop down list. However, once I try to post the view I get the following exception:

键为"FromCurrencyId"的ViewData项的类型为 "System.Int32",但必须为"IEnumerable"类型.

The ViewData item that has the key 'FromCurrencyId' is of type 'System.Int32' but must be of type 'IEnumerable'.

货币控制器

namespace Project.Controllers
{
    public class CurrencyController : Controller
    {
      [HttpGet]
        // GET: Currency
        public ActionResult Index()
        {

            CurrenciesClient Cur = new CurrenciesClient();
            var listCurrency = Cur.findAll().ToList();

            Currencies model = new Currencies();
            model.FromCurrencies = new SelectList(listCurrency, "Id", "CurrencyName");
            model.ToCurrencies = new SelectList(listCurrency, "Id",  "CurrencyName");

            return View(model);

        }

        [HttpPost]
        public ActionResult Index(Currencies cur)
        {


            if (ModelState.IsValid)
            {
                if (cur.FromCurrencyId == cur.ToCurrencyId)
                {
                    //do something if same currecnies and return.
                    ModelState.AddModelError("CurrencyCountry", "Can't make the conversion for the same value");
                }
                else
                {
                   some code .....
                }
            }

            return View(cur);

        }
    }
}

货币VM

namespace Project.ViewModels
{
    public class Currencies
    {
        public int Id { get; set; }
        [Required]
        public int FromCurrencyId { get; set; }
        public SelectList FromCurrencies { get; set; }

        [Required]
        public int ToCurrencyId { get; set; }
        public SelectList ToCurrencies { get; set; }

        public string CurrencyName { get; set; }

        public string CurrencyCountry { get; set; }


        [Required]
        public decimal ConversionRate { get; set; }

        public decimal Value { get; set; }

        public SelectList AvailableCurrencies { get; set; }


    }
}

CurrencyClient Web服务虚拟机

CurrencyClient web service VM

namespace Project.ViewModels
{
    public class CurrenciesClient 
    {
        private string base_Url = "http://localhost:51646/api/";

        public IEnumerable<Currencies> findAll()
        {
            try
            {
                HttpClient client = new HttpClient();
                client.BaseAddress = new Uri(base_Url);
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                HttpResponseMessage response = client.GetAsync("currencies").Result;
                if (response.IsSuccessStatusCode)
                {
                    var resposeData = response.Content.ReadAsStringAsync().Result;
                    var Currency = JsonConvert.DeserializeObject<List<Currencies>>(resposeData);
                    return Currency;


                }
                return null;

            }
            catch
            {
                return null;
            }
        }
    }
}

索引视图

model Project.ViewModels.Currencies

@{
    ViewBag.Title = "Index";
}


@using (Html.BeginForm("Index", "Currency", FormMethod.Post))
{
    @Html.TextBoxFor(m => m.ConversionRate, new { @size = "5" })
    @Html.DropDownListFor(m => m.FromCurrencyId, Model.FromCurrencies as IEnumerable<SelectListItem>)
      @Html.DropDownListFor(m => m.ToCurrencyId, Model.ToCurrencies as IEnumerable<SelectListItem>)
        <button type="submit" class="btn btn-primary">Convert</button>
}

推荐答案

此问题是因为您从下拉列表中传递了 null 值.这意味着您没有选择任何值.检查您是否将从下拉列表中传递一些值是否可以正常工作.要解决此问题,您需要添加相同的值 代码

This problem is becuase you are passing null value from your dropdown.Means you are not selecting any value. Check that if you will pass some value from dropdown it will work fine.To solve this problem you need to add the same code

Currencies model = new Currencies();
            model.FromCurrencies = new SelectList(listCurrency, "Id", "CurrencyName");
            model.ToCurrencies = new SelectList(listCurrency, "Id",  "CurrencyName");

在控制器索引发布方法中.由于selectListitem为null,将执行以下代码

in your controller index post method.Because if selectListitem would be null the following code will be executed

 IEnumerable<SelectListItem> selectList = o as IEnumerable<SelectListItem>;
if (selectList == null)
{
    throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, 
        MvcResources.HtmlHelper_WrongSelectDataType,
        name, o.GetType().FullName, "IEnumerable<SelectListItem>"));
}

哪个将引发异常. (最好使用

Which will throw exception. (It would be better if you will use

ViewBag.FromCurrencies = new SelectList(listCurrency, "Id", "CurrencyName");

像这样.

更好的描述在这里:

此链接中也提供了完整的解释,例如此代码的工作原理.

The whole explanation is also given in this link like how does this code work.

这篇关于如何解决此错误"IEnumerable&lt; SelectListItem&gt;"在下拉列表MVC中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆