如何将模型值绑定到dropdownlist mvc4中的选定项文本

时间:2013-08-06 15:07:26

标签: c# asp.net-mvc-3 html-select

在我的申请中,我有两个下拉列表。首先显示国家/地区值,然后显示所选国家/地区的状态。生成值并在两个下拉列表中显示。但是在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 
}

2 个答案:

答案 0 :(得分:1)

在Html中定义下拉列表时,每个option都有valuetext的属性,text值会显示给用户,{{1}是该下拉列表的“选定值”。将表单发布到控制器时,仅发布value。如果您希望使用名称而不是要发布的ID,只需将下拉列表项的value属性设置为源数据的value

例如,当您填充状态下拉列表时,您可以这样做:

name

答案 1 :(得分:1)

这不是问题。您希望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") })