我正在向我的控制器提出一个模型,
我希望用户如何从下拉菜单中选择国家/地区,所以我将其传递给单独列表中的视图:
控制器GET:
public static List<String> provinces = new List<String>() { "Eastern Cape", "Free State", "Gauteng", "KwaZulu-Natal", "Limpopo", "Mpumalanga", "Northern Cape", "North West", "Western Cape" };
public static List<String> countries = new List<String>() { "South Africa" };
public ActionResult Create()
{
ViewBag.Provinces = provinces.Select(x =>
new SelectListItem()
{
Text = x.ToString()
});
ViewBag.Countries = countries.Select(x =>
new SelectListItem()
{
Text = x.ToString()
});
return View();
}
现在我在视图中显示下拉列表:
....
<p>
@Html.LabelFor(model => model.Province, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownList("Provinces", null, htmlAttributes: new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.Province, "", new { @class = "text-danger" })
</div>
</p>
<p>
@Html.LabelFor(model => model.Country, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownList("Countries",null , htmlAttributes: new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.Country, "", new { @class = "text-danger" })
</div>
</p>
....
这是我的视图模型:
public class RadioNetwork
{
public int NetworkIdentifier { get; set; }
public string CommonName { get; set; }
public string RepeaterName { get; set; }
public string StartCode { get; set; }
public string Frequency { get; set; }
public string Area { get; set; }
public string Province { get; set; }
public string Country { get; set; }
}
所以我发现了问题所在。但我不知道如何解决它。
我需要表单来获取我的DropDown的选定值而不是模型吗?
因为当我在POST控制器中收到视图模型时,普罗旺斯和国家都是“空”
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Create([Bind(Include = "NetworkIdentifier,CommonName,RepeaterName,StartCode,Frequency,Area,Province,Country")] RadioNetwork radioNetwork)
{
答案 0 :(得分:1)
尝试
@Html.DropDownList(m => m.Province, (SelectList)ViewBag.Provinces, ...
这会将所选省份绑定到您的模型
答案 1 :(得分:1)
您的模型没有正确绑定,因为您使用了错误的方法来渲染DropDownLists。表单中的字段根据name
属性绑定到模型,DropDownList()
方法呈现没有该属性的字段。当您希望表单字段正确绑定到模型时,您应该始终注意使用以For
结尾的方法,这样您就不必担心模型绑定。
你正在做
@Html.DropDownList("Countries",null , htmlAttributes: new { @class = "form-control" })
你应该这样做
@Html.DropDownListFor(model => model.Country, (List<SelectListItem>)ViewBag.Countries, new { @class = "form-control" })
此外,您的列表应为:
ViewBag.Provinces = provinces.Select(x =>
new SelectListItem()
{
Text = x.ToString(),
Value = x.ToString()
}).ToList();
P.S。你根本不需要任何绑定的东西。