Sunday, 19 July 2020

Search Functionality in MVC

Step1: In SQL server create database ProductsDB. In this database create one table Product  with following columns


Step2: Create Asp.Net MVC Project named as SearchInMVC and select ‘Empty’ ‘MVC’ template as shown in fig below
Step3: Right click on Models folder & add AdoNet Data Model in which select ‘DB first approach from database’ 

Note: Before adding controller build your solution once

Step4: Right click on Controller folder & add the following controller option
After selecting the above option a new window will open & add Model class & data context class name
This will add all insert update delete operations to our controller. Now run our application and see the result as below.
This is showing complete list of Product in tables 



Now to add search functionality in our project go to controller index action and change the with following code

public ActionResult Index(string searchBy,string search)

        {
            if(searchBy == "Name")
            {
                return View(entities.Products.Where(a => a.Name.StartsWith(search) || search==null).ToList());
            }
            else
            {
                return View(entities.Products.Where(a => a.Feature.StartsWith(search) || search == null).ToList());
            }
            
        }
       
Go to Index.cshtml and add following code

<p>
    <div class="row">
        <div class="col-md-6">
            @Html.ActionLink("Create New", "Create")
        </div>
        <div class="col-md-6">
            @using (Html.BeginForm("Index", "Products", FormMethod.Get))
            {
                <b>Search By:</b> @Html.RadioButton("searchBy", "Name")<text>Name</text>
                @Html.RadioButton("searchBy", "Feature")<text>Feature</text> 
                @Html.TextBox("search")<input type="submit" value="Search" />

            }
        </div>
        </div>
</p>

Again Run our application and see the result same as below


Posted By: pankaj_bhakre

No comments:

Post a Comment