将Json绑定到MVC 4中的DropDownList

时间:2018-03-19 20:02:49

标签: c# asp.net-mvc dropdown

开发人员工具网络标签中的json字符串是:

[{\"id\":\"20\",\"name\":\"System Team\"}]

我的控制器代码是

public class Teams
{
    public int id { get; set; }
    public string name { get; set; }
    public IEnumerable<SelectListItem> names { get; set; }

    public string[] team { get; set; }
}
public ActionResult Teams()
{  
    //Covert JSON to .net object using Deserialize method

    var jsonString ="[{\"id\":\"20\",\"name\":\"System Team\"}]";
    JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
    List<Teams> listTeams = (List<Teams>)javaScriptSerializer.Deserialize(jsonString,typeof(List<Teams>));

    foreach (Teams teams in listTeams)
    {
        Response.Write("" + teams.name + "<br/>");
    }
}

我的观看代码是:

@{
    ViewBag.Title = "Teams";  
}   
@Html.DropDownList("names",null,"--Select Teams--")

如何将 name:system team 的json数据绑定到下拉列表? 我想要&#34;系统团队&#34;作为下拉列表中的值。我正在使用MVC 4 Framework。

1 个答案:

答案 0 :(得分:0)

您可以执行SelectList

之类的操作

在您的控制器中:

public ActionResult Teams()
{  
    //Covert JSON to .net object using Deserialize method
    var jsonString ="[{\"id\":\"20\",\"name\":\"System Team\"}]";
    JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
    List<Teams> listTeams = (List<Teams>)javaScriptSerializer.Deserialize(jsonString,typeof(List<Teams>));

    var teamList = new List<SelectListItem>();
    foreach (Teams teams in listTeams)
    {
        var listItem = new SelectListItem{ Value = teams.id, Text = teams.name };
        teamList.Add(listItem);
    }

    ViewData["teamList"] = teamList;

}

在您看来:

@Html.DropDownList("names", new SelectList((List<SelectListItem>)ViewData["teamList"], "Value", "Text"), "--Select Teams--")