![](/img/trans.png)
[英]How can I change the input element name attribute value in a razor view model using a custom attribute in a model?
[英]How can I use selected value (not model value) as Post Parameter In Razor View?
我正在將模型擺回我的控制器,
我希望用戶如何從下拉列表中選擇國家,所以我將其傳遞給單獨列表中的視圖:
控制器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)
{
嘗試
@Html.DropDownList(m => m.Province, (SelectList)ViewBag.Provinces, ...
這會將選定的省綁定到您的模型
您的模型未正確綁定,因為您使用了錯誤的方法來渲染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();
PS:您根本不需要任何綁定內容。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.