ProductModel.cs
:(上课)
public List<Product> GetSearchedProduct (string Name)
{
try
{
using (garagedbEntities db = new garagedbEntities())
{
List<Product> products = (from x in db.Products
where x.Name LIKE @txtSearch
select x).ToList();
return products;
}
}
catch (Exception)
{
return null;
}
}
search.aspx
:
<%@ Page Title="" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<asp:TextBox ID="txtSearch" runat="server"></asp:TextBox>
<asp:Button ID="btnSearch" runat="server" Text="Button" OnClick="btnSearch_Click" />
<br />
<asp:Panel ID="pnlProducts" runat="server">
<br />
</asp:Panel>
<div style="clear:both"></div>
这是我的search.aspx
文件。实际上我希望从product
获取TextBox
的名称,然后将其传递给检索products
的方法。
答案 0 :(得分:5)
在linq中你应该使用Contains:
List<Product> products = (from x in db.Products
where x.Name.Contains(Name)
select x).ToList();
修改:要使用方法,您应创建ProductModel
的新实例,然后调用GetSearchedProduct
方法并将txtSearch
作为参数发送给它。像这样:
protected void btnSearch_OnClick(object sender, EventArgs e)
{
ProductModel pr = new ProductModel();
var result = pr.GetSearchedProduct(txtSearch.Text);
}