通过多个字段进行MVC WEB API搜索操作

时间:2018-10-11 12:57:41

标签: c# asp.net asp.net-mvc asp.net-web-api

我正在尝试执行搜索操作。我设法以某种方式实现了列的搜索操作。现在,我想搜索多个列。例如,如果我的表格包含姓名,电话号码,电子邮件,性别。 并且如果我搜索单词 M 并且我的名称列包含一个字段为 Mandy ,并且如果我的电子邮件列包含作为 man@mas.com ,我希望它们都显示出来。

我该怎么做?

视图

<td>@Html.TextBoxFor(model => model.name, new { @placeholder = "search by name" })</td>
            <td><input type="submit" value="search" class="btn-success" /></td>

MVC控制器:

[HttpPost]
public ActionResult Index(Customer cvm)
{
    CustomerClient cc = new CustomerClient();
    ViewBag.listCustomers = cc.search(cvm.name);
    return View();
}

客户端类别:

public IEnumerable<Customer> search(int name)
{
    try
    {
        HttpClient client = new HttpClient();
        client.BaseAddress = new Uri(Base_URL);
        client.DefaultRequestHeaders.Accept.Add(new 
            MediaTypeWithQualityHeaderValue("application/json"));
        var result = client.GetAsync(string.Format("customers/search/{0}", name)).Result;
        if (result.IsSuccessStatusCode)
            return result.Content.ReadAsAsync<IEnumerable<Customer>>().Result;
        return null;
    }
    catch
    {
        return null;
    }
}

API控制器:

[HttpGet]
[Route("search/{name}")]
public HttpResponseMessage search(int name)
{
    try
    {
        var httpresponsemessage = new HttpResponseMessage();

        httpresponsemessage.Content = new StringContent(
            JsonConvert.SerializeObject(db.customers.Where(
            p => p.name.Contains(name)).ToList()));

        httpresponsemessage.Content.Headers.ContentType = new
            MediaTypeHeaderValue("application/json");
        return httpresponsemessage;
    }
    catch
    {
        return null;
    }
}

1 个答案:

答案 0 :(得分:3)

假设,如果您使用的是Query,请尝试以下方法之一:

timestamp

如果您使用的是EF,请尝试以下一种,

DECLARE @search NVARCHAR(MAX)

SELECT * 
FROM [TABLE_NAME]
WHERE name LIKE '%' + @search + '%' OR number LIKE '%' + @search + '%' OR
      email LIKE '%' + @search + '%' OR gender LIKE '%' + @search + '%'