I'm working on web application project and I'm trying to include search using ajax.
I created a search form using ajax.beginform() and I have a little problem: When my textbox field is empty and I click on search I want the view to return all the entities(like no search is occurred) , but it returns empty view. I tried to check in the controller if the string is null but no success.
1.what value the parameter gets when the text field is empty?
2.how do I send couple of parameters in this form?
Thank you in advance!
Aviv
.cshtml - View
@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 - Controller
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);
}
When user does not enter anything in the input search box and submit the form, the script will send an empty string. So you should check for null or empty string.
if (!string.IsNullOrEmpty(branchname))
{
model = model.Where(x => x.Branchname.Equals(branchname)).ToList();
}
Also your action method parameter name should match with your input element name.
@Html.TextBox("branchname")
Also, You do not need to call ToList()
before your Where
clause. You can call that at the very end and that time the LINQ query expression will be evaluated and will give you the filtered results. If you want to use the case insensitive search, use one of the case insensitive StringComparison
enum value in the Equals
method overload.
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);
}
If you want to execute multiple filters , add another Where clause on the model
before you call ToList()
(Same as what we did for branchName)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.