ASP.NET MVC +填充的DropDownList [英] ASP.NET MVC + Populate dropdownlist

查看:247
本文介绍了ASP.NET MVC +填充的DropDownList的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的ViewModel我有:

 公共类PersonViewModel
{
    公众人物的人获得{;组; }
    公众诠释SelectRegionId {搞定;组; }
    公共IEnumerable的< SelectListItem>地区{搞定;组; }
}

但我有我的控制器/视图做显示值?我现在拥有的一切:结果
控制器:

 公众的ActionResult的Create()
{
     VAR模型=新ReUzze.Models.PersonViewModel
     {
         人=新的Person()
         地区=新的SelectList(this.UnitOfWork.RegionRepository.Get(),ID,姓名)
     };
     返回查看(模型);
}

查看:

 < D​​IV CLASS =表单组>
     @ Html.LabelFor(型号=> model.Person.Address.Region)
     @ Html.DropDownListFor(型号=> model.SelectRegionId,新的SelectList(Model.Regions,ID,姓名),选择...)
 < / DIV>

但它给出了一个错误是这样的:

 无法隐式转换类型'System.Web.Mvc.SelectList'到'System.Collections.Generic.IEnumerable< System.Web.WebPages.Html.SelectListItem>'。显式转换存在(是否缺少强制转换?)


解决方案

您的ViewModel有型的IEnumerable'的财产,但的SelectList不满足那种类型。
更改code是这样的:

 公共类PersonViewModel
{
    公众人物的人获得{;组; }
    公众诠释SelectRegionId {搞定;组; }
    公众的SelectList地区{搞定;组; }
}

查看:

 < D​​IV CLASS =表单组>
     @ Html.LabelFor(型号=> model.Person.Address.Region)
     @ Html.DropDownListFor(型号=> model.SelectRegionId,Model.Regions,选择...)
 < / DIV>

In my viewModel I have:

public class PersonViewModel
{
    public Person Person { get; set; }
    public int SelectRegionId { get; set; }
    public IEnumerable<SelectListItem> Regions { get; set; }
}

But what do I have to do in my Controller/View to show the values? What I have now:
Controller:

public ActionResult Create()
{
     var model = new ReUzze.Models.PersonViewModel
     {
         Person = new Person(),
         Regions = new SelectList(this.UnitOfWork.RegionRepository.Get(), "Id", "Name")
     };
     return View(model);
}

View:

 <div class="form-group">
     @Html.LabelFor(model => model.Person.Address.Region)
     @Html.DropDownListFor(model => model.SelectRegionId, new SelectList(Model.Regions, "Id", "Name"), "Choose... ")
 </div>

But it gives an error like this:

Cannot implicitly convert type 'System.Web.Mvc.SelectList' to 'System.Collections.Generic.IEnumerable<System.Web.WebPages.Html.SelectListItem>'. An explicit conversion exists (are you missing a cast?)

解决方案

Your ViewModel has a property of type 'IEnumerable', but SelectList does not satisfy that type. Change your code like this:

public class PersonViewModel
{
    public Person Person { get; set; }
    public int SelectRegionId { get; set; }
    public SelectList Regions { get; set; }
}

View:

<div class="form-group">
     @Html.LabelFor(model => model.Person.Address.Region)
     @Html.DropDownListFor(model => model.SelectRegionId, Model.Regions, "Choose... ")
 </div>

这篇关于ASP.NET MVC +填充的DropDownList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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