在MVC 3下拉框 [英] Dropdown boxes in MVC 3

查看:99
本文介绍了在MVC 3下拉框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想实现我认为编辑的地址。

I am trying to implement editing addresses in my view.

这是地址有街道,镇等,也有国内的ID基本字符串。我在我的国家数据库中的表。

An address has basic strings for street, town etc. It also has a country id. I have a table in my database of countries.

在我的控制器我创建的SelectList这些国家:

In my controller I create a SelectList for these countries:

ViewBag.Countries = _countryRepo.GetAll().Select(c => new SelectListItem { Text = c.Name, Value = c.Id });

现在在我看来,我希望能够利用这个选择列表允许用户选择国家。

Now in my view I want to be able to use this select list to allow users to select the country.

我本来以为:

@Html.DropDownList("countryId", (IEnumerable<Country>)ViewBag.Countries, "Select")

我有两个地址:

public class Company() 
{
    public Address HeadOffice { get; set; }
    public Address SecondOffice { get; set; }
}

所以显示视图时,我需要有所示的选择国家。我不认为我能在我的控制器做到这一点,因为如果我选择一个这样的:

So when displaying the view I need to have the select country shown. I don't think I can do this in my controller because if I select one like this:

 ViewBag.Countries = _countryRepo.GetAll().Select(c => new SelectListItem { Text = c.Name, Value = c.Id, Selected = c.Id == model.HeadOffice.Id ? true : false });

这将只为HeadOffice上工作。

This will only work for the HeadOffice.

从我可以有两种选择。有两种不同的选择列表或手动构建在视图中选择列表:

From what I can there are two options. Have two different select lists or manually build the select list in the view:

<select name="HeadOffice.CountryId">
    @foreach(var c in (IEnumerable<Country>)ViewBag.Countries)
    {
         <option value="@c.Id" @(c.Id == Model.HeadOffice.Id ? "selected='true'" : "">@c.Name</option>
    }
</select>

什么是最好的办法吗?双方似乎都错了,不是很好。有没有更好的方式来处理这个问题呢?

What is the best way? Both seem wrong and not nice. Is there a better way to approach this problem?

推荐答案

我会用一个视图模型,它接受国家名单再一次暴露2个不同的列表。这样,你只查询数据库的人,但仍让你查看清洁

I would use a ViewModel that takes in the list of countries once then expose 2 different lists. This way you only query the database ones but still keep you View clean

视图模型:

public class MyViewModel 
{
  public Address HeadOffice { get; set; }
  public Address SecondOffice { get; set; }

  public IEnumerable<Country> Countries { get;set;}

  public IEnumerable<SelectListItem> HeadOfficeCountries
  {
     get 
     {
       return GetCountriesList(Countries, HeadOffice.Id);
     }
  }

  public IEnumerable<SelectListItem> SecondOfficeCountries
  {
     get 
     {
       return GetCountriesList(Countries, SecondOffice.Id);
     }
  }

  private IEnumerable<SelectListItem> GetCountriesList(IEnumerable<Country> countries, int forAddress)
  {
     return countries.Select(c => new SelectListItem { Text = c.Name, Value = c.Id, Selected = c.Id == forAddress ? true : false });
  }
}

这篇关于在MVC 3下拉框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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