【问题标题】:ASP.NET MVC 5 - ajax.beginform() with null parametersASP.NET MVC 5 - 带有空参数的 ajax.beginform()
【发布时间】:2017-10-14 22:57:24
【问题描述】:

我正在开发网络应用程序项目,我正在尝试使用 ajax 进行搜索。

我使用 ajax.beginform() 创建了一个搜索表单,但遇到了一个小问题: 当我的文本框字段为空并且我单击搜索时,我希望视图返回所有实体(例如没有发生搜索),但它返回空视图。 如果字符串为空但没有成功,我尝试检查控制器。

1.文本字段为空时参数取什么值?

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

提前谢谢你!

阿维夫​​p>

.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);
}     

【问题讨论】:

  • "Country" 参数来自哪里...??

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


【解决方案1】:

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

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

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

@Html.TextBox("branchname")

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

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);
}

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

【讨论】:

  • @Html.TextBoxFor(m => m.BranchName, new { @class= "form-control" }) 会更受欢迎,因为它将创建一个输入名称和 ID 都作为 Branchname 并在提交之前触发任何相关验证
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-11-19
  • 1970-01-01
  • 2017-10-31
  • 1970-01-01
  • 1970-01-01
  • 2015-04-03
  • 1970-01-01
相关资源
最近更新 更多