質問

I'm trying to populate the dropdown list from the Json Request but it looks like this:

System.Web.Mvc.SelectListItem
System.Web.Mvc.SelectListItem
System.Web.Mvc.SelectListItem
System.Web.Mvc.SelectListItem

in the dropdown list.

Its got the correct number of elements, but how can I display the value ?

Model:

 // for geographical search
public string[] SelectedLayerName { get; set; }
public IEnumerable<SelectListItem> LayerItem { get; set; }

View:

@Html.DropDownListFor(y => y.SelectedLayerName, new SelectList(Model.LayerItem))

Controller:

HomePageModel hpm = new HomePageModel();     
hpm.LayerItem = new SelectList(this.GetGroupLayers());  

return View(hpm);

private IEnumerable<GroupLayerInfo> GetGroupLayers()
        {
            var url = AppSettingsHelper.GetAppSetting("GroupLayerMapService");
            IEnumerable<GroupLayerInfo> groupLayers = new List<GroupLayerInfo>();

            using (var client = new HttpClient())
            {
                using (HttpResponseMessage response = client.GetAsync(url).Result) // blocking thread
                {
                    if (response.IsSuccessStatusCode)
                    {
                        var agsContent = response.Content.ReadAsStringAsync();
                        string agsContentString = agsContent.Result;

                        var parser = new GroupLayerInfoParser(agsContentString);
                        groupLayers = parser.Parse();
                        return groupLayers;
                    }
                    else
                    {
                        throw new InvalidOperationException(string.Format("Failed download map image {0}. Reason: {1}.", url, response.ReasonPhrase));
                    }
                }
            }
        }

My stack trace looks shows the info I want to display in the dropdownlist like this:

hpm.LayerItem > base > Items > name

役に立ちましたか?

解決 2

Try using the overload of SelecList, in your controller, where you specify the text and data fields:

HomePageModel hpm = new HomePageModel(); 
hpm.LayerItem = new SelectList(this.GetGroupLayers(), "DataField", "TextField"); 
return View(hpm);

"DataField" and "TextField" should be the names of the respective properties on GroupLayerInfo you want in these places.

And then in your view:

@Html.DropDownListFor(y => y.SelectedLayerName, Model.LayerItem)

他のヒント

It is happening because you're creating the list in the controller and again in the view. So, change your view code to

     @Html.DropDownListFor(y => y.SelectedLayerName, Model.LayerItem)
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top