0
對象:是否有可能在ASP.NET MVC創建一個強類型的複雜觀點
public class CountryLanguage
{
public string Country { get; set; }
public string Language { get; set; }
}
視圖模型:
public class CreateComplexObjectViewModel
{
IList<CountryLanguage> SelectedCountryLanguages { get; set; }
}
查看:
@model CreateComplexObjectViewModel
@{
IEnumerable<CountryLanguage> allCountryLanguages = GetAllFromConfigFile();
}
@Html.ListBoxFor(model => model.SelectedCountryLanguages,
allCountryLanguages.Select(cl => new SelectListItem
{
Text = $"{cl.Country} {cl.Language}",
Value = $"{cl.Country}_{cl.Language}"
}))
當我提交此按原樣,我看到以下參數已發佈:
SelectedCountryLanguages=US_en&SelectedCountryLanguages=US_en-US
無法綁定到CountryLanguage
對象。如果我換一切string
當時的所有的工作,但我要做的字符串解析,以獲得不同的值
var selections = new List<CountryLanguage>();
foreach (string countryLanguage in model.SelectedCountryLanguages)
{
string[] parts = countryLanguage.Split("_");
selections.Add(new CountryLanguage
{
Country = parts[0],
Language = parts[1]
});
}
有沒有我可以在CountryLanguage
對象綁定,而無需爲此額外的處理辦法?