如何将模型值绑定到下拉列表mvc4中的选定项目文本
本文关键字:文本 项目 mvc4 下拉列表 模型 绑定 | 更新日期: 2023-09-27 18:26:40
在我的应用程序中,我有两个下拉列表。第一个显示国家值,第二个显示所选国家的状态。这些值将生成并显示在两个下拉列表中。但在发布时,两个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));
这不是问题。您希望下拉列表为您提供选定的值,在这种情况下,该值是ID,而不是文本。因此,我建议您使用以下内容更改ViewModel的属性:
public int StateID { get; set; }
public int CountryID { get; set; }
public SelectList CountryList { get; set; }
public SelectList RegionList { get; set; }
然而,如果你不想要ID,你可以这样定义你的下拉列表:
@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") })