Get identifier and type from Html.DropDownList for 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 for Person, and there is a drop-down list that displays a 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); } 

Html code

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

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

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

I get only the country identifier on behalf of the object in the create method. The country identifier is loaded inside the Person object in the country.

Is there any way to get the identifier and type of country when transferring from the page to the controller?

I know that I pass Html.DropDownListFor (model => model.Country.Id .... from here.

Is there any solution for me to get the id and type in the controller.

thanks

0
source share
1 answer

Passing it through a person’s object is not the best way to do this. Instead, assign an identifier to your drop-down list, for example:

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

and then put this as a parameter in the 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.

0
source

All Articles