在搜索文本框中接收空值

时间:2011-12-02 22:29:19

标签: .net asp.net-mvc-3

我正在尝试创建一个搜索框来查找数据库中的发票。搜索框的代码如下:

@using (Ajax.BeginForm("Search", "Invoice", new AjaxOptions() { HttpMethod = "POST" })) 

{

    <% input id="search-field" name="search" type="text" value="" %/>

    <% input id="search-submit" name="search-submit" type="submit" value=""   %/>

}

public ActionResult Search(FormCollection collection)
{

        if (collection["search-field"] == null)
            return RedirectToAction("Index");
        else
        {
            string id = collection["search-field"].ToString();
            return RedirectToAction("Details", "Invoice", id.Trim());
        }
}

现在问题是我只收到控制器搜索操作的 null 值。

我正在使用MVC3和.NET framework 4.0

在下一个操作中捕获字符串时,我仍然无法接收字符串值:

public ActionResult Details(string id)  {

  if(string.IsNullOrEmpty(id))

  return RedirectToAction("Index"); ==============> Here

  ObjectParameter[] parameters = new ObjectParameter[3];

  parameters[0]= new ObjectParameter("CUSTNMBR", id);
  parameters[1] = new ObjectParameter("StartDate", System.DateTime.Now.Date.AddDays(-90));
  parameters[2] = new ObjectParameter("EndDate", System.DateTime.Now.Date);

  return View(_db.ExecuteFunction<Models.Invoices>("uspGetCustomerInvoices", parameters).ToList<Models.Invoices>());

}

1 个答案:

答案 0 :(得分:1)

主要问题是,您是根据FormCollection元素的id而非input属性搜索name。尝试编写如下代码:

查看:

@using (Ajax.BeginForm("Search", "Invoice", new AjaxOptions() { HttpMethod = "POST" })) 

{

    <input id="search-field" name="search" type="text" value="" />

    <input id="search-submit" name="search-submit" type="submit" />

}

动作:

public ActionResult Search(string search)
{    
    if (string.IsNullOrEmpty(search))
        return RedirectToAction("Index");
    return RedirectToAction("Details", "Invoice", search.Trim());
}

我修改了您的操作,因此您不再需要查询FormCollection