ASP.NET MVC 5 - 带有null参数的ajax.beginform()

时间:2017-10-14 22:57:24

标签: c# jquery ajax asp.net-mvc asp.net-ajax

我正在处理网络应用程序项目,并且我尝试使用ajax包含搜索。

我使用ajax.beginform()创建了一个搜索表单,我有一点问题: 当我的文本框字段为空并且我点击搜索时,我希望视图返回所有实体(就像没有搜索一样),但它返回空视图。 我试图检查控制器是否该字符串为空但没有成功。

1.文本字段为空时参数得到的值是多少?

2.如何以这种形式发送几个参数?

提前谢谢!

特拉维夫

.cshtml - 查看

@using (Ajax.BeginForm("BranchSearch", "Branches",
        new AjaxOptions { HttpMethod = "POST", InsertionMode = InsertionMode.Replace, UpdateTargetId = "searchResults" }))
{
    <h3>Search:</h3>
    <p>Branch name :</p>@Html.TextBox("Search", null, new { id = branchname"})
    <input type="submit" value="Search" class="btn btn-primary" />
}

.cs - 控制器

public PartialViewResult BranchSearch(String branchname, String country)
{
   List<Branches> model = (from p in db.Branches
                       select p).ToList();

   if(branchname!=null)
      {
        model = model.Where(x => x.BranchName.Equals(branchname)).ToList();
      }

        return PartialView("BranchSearch",model);
}     

1 个答案:

答案 0 :(得分:2)

当用户未在输入搜索框中输入任何内容并提交表单时,脚本将发送一个空字符串。所以你应该检查null或空字符串。

if (!string.IsNullOrEmpty(branchname))
{
    model = model.Where(x => x.Branchname.Equals(branchname)).ToList();
}

此外,您的操作方法参数名称应与您的输入元素名称匹配。

@Html.TextBox("branchname")

此外,您无需在ToList()子句之前致电Where。您可以在最后调用它,那时将评估LINQ查询表达式并为您提供过滤结果。如果要使用不区分大小写的搜索,请在StringComparison方法重载中使用不区分大小写的Equals枚举值之一。

public PartialViewResult BranchSearch(String branchname, String country)
{
    IQueryable<Branch> model = db.Branches;
    if (!string.IsNullOrEmpty(branchname))
    {
        model = model.Where(x => x.BranchName.Equals(branchname
                                      ,StringComparison.OrdinalIgnoreCase));
    }
    // Now we are ready to query the db and get results. Call ToList()
    var result = model.ToList();
    return PartialView("BranchSearch", result);
}

如果要执行多个过滤器,请在调用model之前在ToList()上添加另一个Where子句(与我们对branchName所做的相同)