这是我的VM
public class CountriesViewModel
{
public string CurrentCountry { get; set; }
public IEnumerable<Country> Countries { get; set; }
}
使用我的控制器
public class FiltersController : Controller
{
public ActionResult _ShipToCountry(IEnumerable<Country> countries,
string currentCountry = "AE")
{
var viewModel = new CountriesViewModel
{
Countries = countries.OrderBy(x => x.Name),
CurrentCountry = currentCountry
};
return PartialView(viewModel);
}
}
最后是视图
@Html.DropDownListFor(x => x.Countries,
new SelectList(Model.Countries.ToList(),
"Code", "Name", Model.CurrentCountry))
Model.CurrentCountry是Code。
正确呈现DDL
...
<option value="UA">Ukraine</option>
<option value="AE">United Arab Emirates</option>
<option value="UK">United Kingdom</option>
....
但没有国家被选中,我缺少什么?
答案 0 :(得分:1)
您应该将CurrentCountry
道具设置为表达式,否则您也无法在表单提交中获得所选国家/地区。
@Html.DropDownListFor(x => x.CurrentCountry,
new SelectList(Model.Countries.ToList(), "Code", "Name"))
答案 1 :(得分:0)
这有效......
而不是
@Html.DropDownListFor(x => x.Countries,
new SelectList(Model.Countries.ToList(),
"Code", "Name", Model.CurrentCountry))
用于
@Html.DropDownList(Model.CurrentCountry,
new SelectList(Model.Countries.ToList(),
"Code", "Name", Model.CurrentCountry))