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

时间:2016-02-07 13:27:30

标签: c# asp.net asp.net-mvc model-binding html.dropdownlistfor

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

  

其他信息:DataBinding:'System.String'不包含名为'DealerName'的属性。

我正在使用的服务是返回经销商详细信息列表,我将在mvc中显示该网格,其中包含经销商名称声明月<的两个下拉列表/ strong>用于搜索条件。所以,我创建了一个ViewModel来累积服务的结果,并使用两个addtional属性来在下拉列表中进行绑定。以下是代码:

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的控制器:

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的内容,请提供帮助。

1 个答案:

答案 0 :(得分:1)

生成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>