从Html.DropDownList获取ID和类型到控制器 [英] Get Id and Type from Html.DropDownList to Controller

查看:105
本文介绍了从Html.DropDownList获取ID和类型到控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一堂课

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",并且有一个下拉列表显示了国家/地区列表.

My MVC View Page is Strongly typed to Person and there is a dropdownlist which show the list of countries.

在我的控制器索引中

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方法

When the page is submitted Create method is called in the controller

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

在创建方法"中,我仅从对象人员那里获得国家/地区ID".国家/地区ID已加载到国家/地区下的人员对象中.

I am getting only the Country Id from the object person in the Create Method. The Country Id is loaded inside the Person Object under Country.

当从页面传递到控制器时,是否可以通过任何方式获取国家/地区的ID和类型?

Is there any way I can get both the Id and Type of the country when passed from the Page to the Controller?

我知道我要从此处传递Html.DropDownListFor(model => model.Country.Id ....

I know I am passing Html.DropDownListFor(model => model.Country.Id .... from here.

是否有任何解决方案,以便我在控制器中获取ID和Type.

Is there any Solution so that I get Id and Type in the controller.

谢谢

推荐答案

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

Passing it through the person object is not the best way to do it. Instead, assign an ID to your dropdown list like this:

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

,然后将其作为您的Create方法的参数:

and then put that in as a parameter to your Create method:

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

   person.Country = country;
   ...
}

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

ASP .NET MVC will look for a control that has the same ID name as the parameter in the method call and pass it through.

这篇关于从Html.DropDownList获取ID和类型到控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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