即使使用ToString(),我的搜索方法也无法使用数字

时间:2012-09-05 09:07:27

标签: c# asp.net-mvc-3 ado.net search-form

如您所见,我有一种从表中检索字段的方法。在我看来,我在两个文本框中进行搜索。

ClientID 字符串,所以没问题。但是 OrderId 是一个 Int ,所以我使用ToString()但它仍然不起作用。

我为OrderId编写第二个IF条件的方式错了吗?谢谢你的帮助

public ActionResult Search(string searchString, string searchOrder)
{  
    var user = from m in db.Order   
               select m;

    if (!String.IsNullOrEmpty(searchString))
    {
        user = user.Where(s => s.Order.ClientID.Contains(searchString));
    }         

    if (!String.IsNullOrEmpty(searchOrder))
    {
        user = user.Where(c => c.Order.OrderId.ToString().Contains(searchOrder));
    }

    return this.View("Order", "PrintView", user);
}

2 个答案:

答案 0 :(得分:2)

听起来你应该将searchOrder解析为整数,然后使用:

user = user.Where(c => c.Order.OrderId == targetOrderId);

除此之外,你真的想要{15}的searchOrder匹配订单2150吗?这听起来不太有用。

答案 1 :(得分:0)

要使用数字进行搜索,请将相关方法更改为以下内容:

 public ActionResult PrintOrders(string searchString, int searchOrder = 0)
    {
        var user = from m in db.OrderDetails   
                   select m;

        if (!String.IsNullOrEmpty(searchString))
        {
            user = user.Where(s => s.Order.ClientID.Contains(searchString));               
        }

        if (searchOrder > 0)
        {
            user = user.Where(c => c.Order.OrderId == searchOrder);               
        }

        return this.ViewPdf("Order", "PrintView", user);
    }

另一种方法是:

    public ActionResult PrintOrders(string searchString, string searchOrder)
    { 
        var user = from m in db.OrderDetails   
                   select m;

        if (!String.IsNullOrEmpty(searchString))
        {
            user = user.Where(s => s.Order.ClientID.Contains(searchString));               
        }

        int tmp = Int32.Parse(searchOrder);

        if (tmp != 0)
        {
            user = user.Where(c => c.Order.OrderId == tmp);
        }

        return this.ViewPdf("Order", "PrintView", user);
    }

视图看起来像这样:

@using (Html.BeginForm("PrintOrders", "Historic", FormMethod.Get, new { target = "_blank" }))
{

   Search by Client ID : @Html.TextBox("searchString")

   Search by Order ID : @Html.TextBox("searchOrder")

  <input type="submit" value="Search" />
}