我正在尝试从Json请求填充下拉列表,但它看起来像这样:
System.Web.Mvc.SelectListItem
System.Web.Mvc.SelectListItem
System.Web.Mvc.SelectListItem
System.Web.Mvc.SelectListItem
在下拉列表中。
它有正确数量的元素,但我该如何显示值?
型号:
// for geographical search
public string[] SelectedLayerName { get; set; }
public IEnumerable<SelectListItem> LayerItem { get; set; }
查看:
@Html.DropDownListFor(y => y.SelectedLayerName, new SelectList(Model.LayerItem))
控制器:
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));
}
}
}
}
我的堆栈跟踪外观显示了我想要在下拉列表中显示的信息,如下所示:
hpm.LayerItem&gt;基数&gt;项目&gt;名称
答案 0 :(得分:1)
这种情况正在发生,因为您正在控制器中创建列表并再次在视图中创建列表。 因此,请将您的视图代码更改为
@Html.DropDownListFor(y => y.SelectedLayerName, Model.LayerItem)
答案 1 :(得分:0)
尝试在控制器中使用SelecList
的重载,您可以在其中指定文本和数据字段:
HomePageModel hpm = new HomePageModel();
hpm.LayerItem = new SelectList(this.GetGroupLayers(), "DataField", "TextField");
return View(hpm);
&#34;数据字段&#34;和&#34; TextField&#34;应该是您在这些地方GroupLayerInfo
所需的相应属性的名称。
然后在你看来:
@Html.DropDownListFor(y => y.SelectedLayerName, Model.LayerItem)