从Html.DropDownList获取Id和Type到Controller

时间:2011-08-22 06:23:42

标签: asp.net-mvc-3 c#-4.0 drop-down-menu

我有一个名为

的班级
public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public Country Country { get; set; }
}

public class Country
{
    public int Id { get; set; }
    public string Type { get; set; }
}

我的MVC查看页面是强类型的人,并且有一个显示国家列表的下拉列表。

在我的控制器索引

public ActionResult Index()
{
    LoadCountryList();
    return View(Person);
}

private void LoadCountryList()
{
    IEnumerable<CountryList> countryList = CountryListService.GetCountryList();
    ViewData["CountryList"] = new SelectList(country, "Id", "Type", 0);
}

html中的代码

<%: Html.DropDownListFor(model => model.Country.Id, (IEnumerable<SelectListItem>)ViewData["CountryList"], "--Select--")%>

提交页面时在控制器中调用Create方法

public ActionResult Create(Person person)
{
    // person.Country.Id has the value
    // person.Country.Type is null
}

我在“创建方法”中仅从对象人处获取国家/地区ID。国家标识加载在国家/地区的人员对象内。

从页面传递到控制器时,有什么方法可以同时获得国家/地区的ID和类型?

我知道我从这里传递了Html.DropDownListFor(model =&gt; model.Country.Id ....

是否有任何解决方案,以便我在控制器中获得Id和Type。

由于

1 个答案:

答案 0 :(得分:0)

将其传递给person对象并不是最好的方法。而是将ID分配给下拉列表,如下所示:

<%: Html.DropDownListFor(
      model => model.Country.Id, 
      (IEnumerable<SelectListItem>)ViewData["CountryList"], "--Select--")
      new { id = "CountryID" }
%>

然后将其作为参数添加到Create方法中:

public ActionResult Create(Person person, int CountryID)
{
   var country = CountryListService.GetCountryList().Where(x => x.id == CountryID);

   person.Country = country;
   ...
}

ASP .NET MVC将查找与方法调用中的参数具有相同ID名称的控件并将其传递。

相关问题