2012-09-01 48 views
0

我注意到下面的行爲,並想知道爲什麼「Model.CountryList」在POST時爲空?如果這是默認的MVC行爲還是我們有什麼可以擺脫的呢?這是DropDownListFor MVC中的默認行爲?

型號

public class CountryMaster 
{ 
    public int CountryCode { get; set; } 
    public string CountryName { get; set; } 
} 

視圖模型

public class HomeViewModel 
{ 
    public int SelectedCountry { get; set; } 
    public List<CountryMaster> CountryList { get; set; } 
} 

查看

@model Demo.Web.ViewModels.HomeViewModel 
@Html.DropDownListFor(model => model.SelectedCountry, new SelectList(Model.CountryList, "CountryCode", "CountryName"), "---SELECT COUNTRY---" new { @class = "chosen", @onchange = "this.form.action='/Home/Index'; this.form.submit(); " }) 

注 - 上面DDL的與兩個屬性「SelectedCountry」&「CountryList」綁定。

控制器

在「索引」,HTTPGET方法,讓「CountryList」一些數據庫命中,

public ActionResult Index() 
    { 
     var homeViewModel = new HomeViewModel(); 
    **//get all countries and fill 「CountryList」** 
     homeViewModel.CountryList = _commonService.GetCountriesList(); 
     return View(homeViewModel); 
    } 

現在,當我們選擇在DDL一個項目,並擊中立柱,然後在「Index」,HttpPost,「SelectedCountry」中填充了一些值,但「CountryList」爲NULL,爲什麼?

請幫我理解我爲什麼「CountryList」是NULL,並且有什麼方法可以保持相同?

[HttpPost] 
    public ActionResult Index(HomeViewModel homeViewModel) 
    { 
    /**/ selectçountryValue = 2** 
     var selectçountryValue = homeViewModel.SelectedCountry; 
    **// CountryListAtPost = null** 
     var CountryListAtPost = homeViewModel.CountryList; 

回答

0

根據HttpPost,View將所有FormCollection返回給控制器。所以它始終具有存儲在表單元素中的值,例如文本框,下拉列表或隱藏字段。

在你的情況下,homeViewModel必須包含SelectedCountry屬性的值,因爲它在表單集合中並與DropDown元素關聯,但CountryList與任何元素都沒有關聯,所以它返回null。

將查看返回到控制器查找this線程。

祝您好運!

+0

謝謝你給我的理由(表格收集的東西),但問題是,如果我們檢查上面的視圖代碼綁定dropdownlistfor,我們使用了兩個屬性1. SelectedCountry&2. CountryList,那麼爲什麼「countrylist」不在表單集合中? – user584018

+0

正如我所說,在我的回答中,「countrylist」與任何表單元素沒有關聯 –

+0

好吧......得到它......謝謝,但很難將「countrylist」與任何表單元素相關聯......可能是隱藏的字段幫助我? – user584018

0

非常感謝Kundan,多隱場就能解決問題,

@Html.DropDownListFor(model => model.SelectedCountry, new SelectList(Model.CountryList, "CountryCode", "CountryName"), "---SELECT COUNTRY---", 
            new { @class = "chosen", @onchange = "this.form.action='/Home/Index'; this.form.submit(); " }) 
      @if (Model.CountryList != null) 
      { 
       for (int i = 0; i < Model.CountryList.Count; i++) 
       { 
        @Html.HiddenFor(model => model.CountryList[i].CountryCode) 
        @Html.HiddenFor(model => model.CountryList[i].CountryName) 
       } 
      }