繁体   English   中英

绑定ASP.NET MVC中的下拉列表时出错

[英]Error binding a dropdown list in ASP.NET MVC

我正在尝试使用一个提供经销商列表的Web API,并尝试将其绑定到mvc中的DropdownList中。 但是,我遇到了一个错误:

附加信息:数据绑定:“ System.String”不包含名称为“ DealerName”的属性。

我正在使用的服务将返回经销商详细信息列表,并且必须将其显示在mvc中的Web网格中,并带有两个下拉列表,列出了“ 经销商名称”和“ 声明月”作为搜索条件。 因此,我创建了一个ViewModel来累积来自服务的结果,并带有两个附加属性以用于绑定到下拉列表中。 以下是代码:

Web服务结果 -此类的IEnumerable列表:

public class DealerReportResponse
{
    public string DealerCode { get; set; }
    public string DealerName { get; set; }
    public string StatementReceivedOnDate { get; set; }
    public int StatementReceivedOnDay { get; set; }
    public string StatementReceivedOnMonth { get; set; }
}

我的视图模型是:

public class DealerReportViewModel
{
    public List<string> DealerName { get; set; }
    public List<string> DealerStatementMonth { get; set; }
    public List<DealerReportResponse> DealerReportDetails { get; set; }
}

这是我要将模型传递给View的Controller:

public ActionResult Index()
{
      try
      {
          DealerReportViewModel model = new DealerReportViewModel();
          var serviceHost = //url;
          var service = new JsonServiceClient(serviceHost);
          var response = service.Get<IEnumerable<DealerReportResponse>>(new DealerReportRequest());
          if (response != null)
          {
               model.DealerName = response.Select(x => x.DealerName).Distinct().ToList();
               model.DealerStatementMonth = response.Select(x => x.StatementReceivedOnMonth).Distinct().ToList();
               model.DealerReportDetails = response.ToList();
               return View("DealerReportGrid", model);
           }
           else
           {
               //do something
           }
       }
       catch (Exception ex)
       {
            //catch exception
       }
 }

并且在视图中,我试图将模型绑定到一个下拉列表中,如下所示:

<!-- Search Box -->
@model DealerFinancials.UI.Models.DealerReport.DealerReportViewModel
<div id="searchBox">
    @Html.DropDownListFor(m => m.DealerName, 
         new SelectList(Model.DealerName, "DealerName", "DealerName"),
         "All Categories", 
         new { @class = "form-control", @placeholder = "Category" })
</div>

但是,我无法将DealerName列表绑定到下拉列表。 我不确定该错误。 如果我缺少将模型传递给View的东西,请提供帮助。

生成SelectList时出错:您需要从Model.DealerReportDetails而不是从Model.DealerName生成它。 因此,不要使用new SelectList(Model.DealerName, "DealerName", "DealerName")使用new SelectList(Model.DealerReportDetails , "DealerName", "DealerName")

@model DealerFinancials.UI.Models.DealerReport.DealerReportViewModel
<div id="searchBox">
    @Html.DropDownListFor(m => m.DealerName, 
         new SelectList(Model.DealerReportDetails , "DealerName", "DealerName"),
         "All Categories", 
         new { @class = "form-control", @placeholder = "Category" })
</div>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM