开发者

Get Id and Type from Html.DropDownList to Controller

I have a class called

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; }
}

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

In My Controller Index

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

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

Code in the html

<%: Html.DropDownListFor(model =开发者_如何学JAVA> model.Country.Id, (IEnumerable<SelectListItem>)ViewData["CountryList"], "--Select--")%>

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
}

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.

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

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

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

Thanks


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" }
%>

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 will look for a control that has the same ID name as the parameter in the method call and pass it through.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜