2011-08-22 33 views
0

我有一個名爲獲取標識和類型來控制

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查看頁面是強類型到人,有一個下拉列表,其顯示的國家列表類。

在HTML

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

當提交頁面創建方法,我的控制器指數

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

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

代碼被稱爲控制器

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

我只得到來自創建方法中的對象人員的國家/地區ID。 Country Id在國家下的Person Object內加載。

有沒有什麼辦法可以在頁面傳遞給控制器​​時同時獲得國家的Id和Type?

我知道我傳遞Html.DropDownListFor(型號=> model.Country.Id ....從這裏開始。

是否有任何解決方案,使我得到的標識和類型的控制器。

感謝

+0

看看這裏http://stackoverflow.com/questions/7409394/html-dropdownlist-mvc3-confusion/8336039#8336039 –

回答

0

通過人物對象傳遞它不這樣做的最佳方式相反,分配一個ID給您的下拉列表這樣的:

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

,然後把在作爲參數的創建方法:

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

    person.Country = country; 
    ... 
} 

ASP .NET MVC將查找具有相同的ID名稱作爲方法調用的參數的控制,並通過它傳遞。