[英]how to bind model value to selected item text from dropdownlist mvc4
在我的應用程序中,我有兩個下拉列表。 首先顯示國家/地區值,然后顯示所選國家/地區的狀態。 生成值並在兩個下拉列表中顯示。 但是在post上,兩個dropdownlist都返回模型值的id而不是名稱或值。 如何在帖子上綁定下拉列表的選定項目文本? 型號:
public string State { get; set; }
public string Country { get; set; }
public SelectList CountryList { get; set; }
public SelectList RegionList { get; set; }
public class Countries
{
public string ID { get; set; }
public string Name { get; set; }
}
public class Region
{
public string ID { get; set; }
public string Name { get; set; }
}
視圖
@Html.DropDownListFor(model =>model.State, new SelectList(Model.RegionList, "Value", "Text", Model.RegionList.SelectedValue))
@Html.DropDownListFor(model => model.Country, new SelectList(Model.CountryList, "Value", "Text", Model.CountryList.SelectedValue), new { data_url = Url.Action("GetRegionDetail", "WPindex") })
<script type="text/javascript">
$(document).ready(function () {
$("#Country").change(function () {
$("#State").empty();
var url =$(this).data(url);
var Id = $('#Country option:selected').attr('value');
$.getJSON(url, { ID: Id },
function (data) {
jQuery.each(data, function (key, Region) {
$("#State").append($("<option></option>").val(Region.ID).html(Region.Name));
}
);
});
});
});
</script>
控制器:
public JsonResult GetRegionDetail(int ID)
{
AddressModel amodel = new AddressModel();
List<Model.Region> objRegion = new List<Model.Region>();
objRegion = GetRegionList(ID);
SelectList objlistofRegiontobind = new SelectList(objRegion, "ID", "Name", 0);
amodel.RegionList = objlistofRegiontobind;
return Json(objRegion, JsonRequestBehavior.AllowGet);
}
[HttpPost]
public ActionResult UpdateDetails(Model objmodel)
{
string state = objmodel.State; // returns ID and not Name (selected text)
string country = objmodel.Country; // returns ID and not Name
}
在Html中定義下拉列表時,每個option
都有一個value
和text
屬性, text
值顯示給用戶, value
是該下拉列表的“選定值”。 將表單發布到控制器時,僅發布該value
。 如果您希望使用名稱而不是要發布的ID,只需將下拉列表項的value
屬性設置為源數據的name
。
例如,當您填充狀態下拉列表時,您可以這樣做:
$("#State").append($("<option></option>").val(Region.Name).html(Region.Name));
那不是問題。 您希望DropDownList為您提供所選的值,在這種情況下,ID是ID,而不是Text。 因此,我建議您使用以下內容更改ViewModel的屬性:
public int StateID { get; set; }
public int CountryID { get; set; }
public SelectList CountryList { get; set; }
public SelectList RegionList { get; set; }
但是,如果您不想要ID,可以像這樣定義DropDownLists:
@Html.DropDownListFor(model => model.State, new SelectList(Model.RegionList, Model.State))
@Html.DropDownListFor(model => model.Country, new SelectList(Model.CountryList, Model.Country), new { data_url = Url.Action("GetRegionDetail", "WPindex") })
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.