簡體   English   中英

ASP.NET MVC 5-具有空參數的ajax.beginform()

[英]ASP.NET MVC 5 - ajax.beginform() with null parameters

我正在研究Web應用程序項目,並且正在嘗試包括使用Ajax進行的搜索。

我使用ajax.beginform()創建了一個搜索表單,但有一個小問題:當我的文本框字段為空並且單擊搜索時,我希望視圖返回所有實體(就像未進行搜索一樣),但是它返回空視圖。 我試圖在控制器中檢查字符串是否為null但沒有成功。

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

當用戶未在輸入搜索框中輸入任何內容並提交表單時,腳本將發送一個空字符串。 因此,您應該檢查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所做的操作相同)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM