ASP.NET MVC下拉列表没有选择值

时间:2013-11-23 12:49:40

标签: c# asp.net asp.net-mvc entity-framework razor

环境ASP.net MVC5 +实体框架代码优先

public class Vender
{
    public int VenderID { get; set; }


    public string VenderCode { get; set; }


    public string CompanyCode { get; set; }


    public string CompanyFullName { get; set; }


    public string CreateUser { get; set; }


    public int VenderCityId { get; set; }

}

对于VenderCityId喜欢另一个班级“城市”,它有ID和名称

我有一个VenderViewModel

public class VenderViewModel
{

    public Vender Vender;

    public VenderViewModel(IVenderRepository _venderRepository,int? Id)
    {
        if (Id==null)
        {
            Vender = new Vender();
        }
        else
        {
            Init(_venderRepository, Id);
        }
    }

    private void Init(IVenderRepository _venderRepository, int? Id)
    {
        Vender = _venderRepository.GetVenderById(Id);

    }


    public IEnumerable<SelectListItem> CityItems
    {
        get
        {
            IEnumRepository cityEnumRepository=new EnumRepository(new MasterDataContext());
            IEnumerable<City> _city = cityEnumRepository.GetAll<City>();

            var allCitys = _city.Select(m => new SelectListItem
            {
                Value = m.Id.ToString(),
                Text = m.Name

            });
            //return allCitys;
            return DefaultCity.Concat(allCitys);
        }
    }

    public IEnumerable<SelectListItem> DefaultCity
    {
        get
        {
            return Enumerable.Repeat(new SelectListItem
            {
                Value = "-1",
                Text = "Select a City"
            }, count: 1);
        }
    }

这是关于控制器的,只是简单的

public ActionResult Edit(int? id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        //Vender vender = _venderRepository.GetVenderById(id);
        VenderViewModel vm = new VenderViewModel(_venderRepository, id);
        if (vm.Vender == null)
        {
            return HttpNotFound();
        }
        return View(vm);
    }

从调试中,我可以确认此viewmodel具有VenderCityId的值。

最后的观点:

 @Html.DropDownListFor(model => model.Vender.VenderCityId, Model.CityItems)

问题是下拉列表无法显示正确的项目。加载后没有选择任何项目。

1 个答案:

答案 0 :(得分:2)

您需要通过添加以下内容在CityItems中选择ID:

 Selected = VenderID.Equals(x.Key)

填充SelectList时,请执行以下操作:

var allCitys = _city.Select(m => new SelectListItem
            {
                Value = m.Id.ToString(),
                Text = m.Name,
                Selected = VenderID.Equals(m.Id.ToString())

            });

然后将您的Html助手更改为:

@Html.DropDownListFor(model => model.Vender.VenderCityId, Model.CityItems, "Please select ")

这将使用强类型对象,而不是使用ViewBag