2012-09-27 93 views
1

我試圖讀取一些數據在JSON中,反序列化它,並將它顯示在我的視圖中的DropDownList中。數據看起來像這樣:ASP.NET MVC -JsonConvert.DeserializeObject到Html.DropDownList

{ 
    "products": [ 
    { 
     "body_html": "<p> ....</p>", 
     "created_at": "2012-09-19T11:55:44-04:00", 
     ... 
     "tags": "Emotive, Flash Memory, MP3, Music", 
     "variants": [ 
     { 
      "compare_at_price": null, 
      "created_at": "2012-09-19T11:55:44-04:00", 
      ... 
      "inventory_quantity": 10 
     } 
     ], 
     "images": [ 
     { 
      "created_at": "2012-09-19T11:55:44-04:00", 
      "id": 850703190, 
      ... 
     } 
     ] 
    } 
    ] 
} 

我已經嘗試了一些不起作用的不同的東西。現在,我有我的控制器:

var data = Newtonsoft.Json.Linq.JObject.Parse(productsJson.ToString())["products"]; 
SelectList productsData = JsonConvert.DeserializeObject<SelectList>(data.ToString()); 
ViewData["products"] = productsData; 

並在視圖:

@Html.DropDownList("ProductList", (SelectList)ViewData["products"]) 

目前,我發現了以下錯誤:

Cannot create and populate list type System.Web.Mvc.SelectList.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.InvalidOperationException: Cannot create and populate list type System.Web.Mvc.SelectList.

幫助表示讚賞。

+0

什麼文字,你試圖把在選擇列表中?我沒有看到任何好的候選人。 – McGarnagle

回答

0

首先,你要解析JSON到您的產品類型,然後你可以使用這樣的:

var products = new SelectList(parsedProductList,"valueField here", "textField here"); 
0

products在您的JSON中與SelectList類型不兼容。 嘗試手動填寫SelectList。

1

我給你另一種解決方案的,在我的控制器JSON

填寫您的下拉列表,我有一個動作並填寫我的狀態,國家選擇

公共JsonResult國家(INT countryId) {

var stateList = CityRepository.GetList(countryId); 
    return Json(stateList, JsonRequestBehavior.AllowGet); 
} 

在我看來,我結合我州DROPDOWNLIST這樣

<script type="text/javascript"> 
    function cascadingdropdown() { 
     $("#stateID").empty(); 
     $("#stateID").append("<option value='0'>--Select State--</option>"); 
     var countryID = $('#countryID').val(); 
     $.ajax({ 
      url: "/City/State", 
      dataType: 'json', 
      data: { countryId: countryID }, 
      success: function (data) { 
       $("#stateID").empty(); 
       $("#stateID").append("<option value='0'>--Select State--</option>"); 
       $.each(data, function (index, optiondata) { 
        alert(optiondata.StateName); 
        $("#stateID").append("<option value='" + optiondata.ID + "'>" + optiondata.StateName + "</option>"); 
       }); 
      }, 
      error: function() { 
       alert('Faild To Retrieve states.'); 
      } 

     }); 
    } 
</script> 

我認爲這將有助於你...

相關問題