【问题标题】:Get Id and Type from Html.DropDownList to Controller从 Html.DropDownList 获取 Id 和 Type 到 Controller
【发布时间】:2011-08-22 06:23:42
【问题描述】:

我有一门课叫

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 视图页面强类型为 Person,并且有一个显示国家列表的下拉列表。

在我的控制器索引中

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
}

我在 Create 方法中只从对象 person 那里获得 Country Id。 Country Id 加载在 Country 下的 Person 对象中。

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

我知道我正在传递 Html.DropDownListFor(model => model.Country.Id .... 从这里。

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

谢谢

【问题讨论】:

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


【解决方案1】:

通过 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 名称的控件并将其传递。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-30
    相关资源
    最近更新 更多