2017-10-14 134 views
0

我正在處理web應用程序項目,我試圖包括使用ajax搜索。ASP.NET MVC 5 - ajax.beginform()與空參數

我使用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); 
}  
+0

哪裏是從哪裏來的「國家」參數... ?? –

回答

2

當用戶不輸入搜索框中輸入任何內容,並提交表單,該腳本將發送一個空字符串。所以你應該檢查空字符串或空字符串。

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

如果要執行多個過濾器,添加一個Where子句在model你打電話ToList()(同我們所做的分支名稱)之前

+1

非常感謝!它的工作:) –

+0

** @ Html.TextBoxFor(m => m.BranchName,new {@class =「form-control」})**會更受歡迎,因爲它會創建一個名稱和ID爲Branchname並且在提交之前也會觸發任何相關驗證 –