当我尝试设置DataSource

时间:2015-11-15 16:23:25

标签: asp.net entity-framework linq webforms model-binding

我有一个显示正常的ListView。但是,当我尝试以编程方式设置DataSource时会抛出此错误:

DataSource or DataSourceID cannot be defined on 'ListView1' when it uses model binding.

这是我的按钮代码的外观:

protected void btSearch_Click(object sender, EventArgs e)
{
  string searchValue = tbSearch.Text;
  if (!string.IsNullOrWhiteSpace(searchValue))
  {
    using (WalkContext db = new WalkContext())
    {          
      var query = (from w in db.DogWalks.Include("Pictures")
                   where w.Title.Contains(searchValue)
                   select w);

        ListView1.DataSource = query;
        ListView1.DataBind();
    }
  }
}

这是我的ListView

的摘录
<asp:ListView ID="ListView1" runat="server" DataKeyNames="WalkID" ItemType="DogWalks.DAL.DogWalk" SelectMethod="ListView1_GetData">
<ItemTemplate>
  <div class="row">
    <div class="col-md-3">
       <asp:Image ID="Image1" class="img-responsive pull-left" style="min-width:262.5px;min-height:150px;" runat="server" ImageUrl=<%# Item.Pictures.FirstOrDefault().PictureUrl %>/>
    </div>
    <div class="col-md-9">
      <a href="/Walks/WalkDetails?WalkID=<%#Item.WalkID%>">
         <h3><b><%# Item.Title%></b></h3>
      </a>
      ...
    </div>
  </div>
</ItemTemplate>

我可以在调试器中看到查询返回正确数量的结果,我似乎无法让Listview接受查询。我还尝试添加.toList(),但这并没有解决问题。

1 个答案:

答案 0 :(得分:0)

错误非常自我解释。在您的视图中使用Model Binding@model MultiShop.Panel.Models.Product.AddProductFeatureTextModel <div id="featureText-@Model.TypeId"> @Html.HiddenFor(m => m.TypeId) @Html.HiddenFor(m => m.IsRequired) @Html.HiddenFor(m => m.Name) @Html.Label(Model.Name) @Html.TextBoxFor(m => m.Value) @if (Model.IsRequired) { <span class="requiredField"></span> } @Html.ValidationMessageFor(m => m.Value) <div class="showDictionariesList"> @Html.EditorFor(m => m.ShowDictionaries) </div> @Html.DropDownListFor(m => m.SelectedDictionaryItemId, new SelectList(Model.DictionaryItems, "Id", "Value", Model.SelectedDictionaryItemId)) <input type="button" value="Save" onclick="@("submitAjaxForm('#featureText-" + @Model.TypeId + "')")" /> </div> )时,您无法设置DataSource。 您需要从&lt; btSearch_Click&#39;移动查询逻辑。到SelectMethod="ListView1_GetData"方法