我注意到下面的行爲,並想知道爲什麼「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;
謝謝你給我的理由(表格收集的東西),但問題是,如果我們檢查上面的視圖代碼綁定dropdownlistfor,我們使用了兩個屬性1. SelectedCountry&2. CountryList,那麼爲什麼「countrylist」不在表單集合中? – user584018
正如我所說,在我的回答中,「countrylist」與任何表單元素沒有關聯 –
好吧......得到它......謝謝,但很難將「countrylist」與任何表單元素相關聯......可能是隱藏的字段幫助我? – user584018