Sunday, 27 March 2016

Implementing searching functionality in ASP.NET MVC Application

Leave a Comment

Searching in ASP.NET MVC Using Entity framework:

Introduction:
Hello every one welcome once again thanks for the previous post comments.In this post we are going to learn how to create search functionality in MVC application using Entity framework(Object relational mapping tool for database operations) and LINQ (Language integrated Query).i will explain about both these thing later in next posts.

I will explain this tutorial in a step by step manner.
Step 1: Open Visual studio and create ASP.NET MVC application using Empty template

Searching in ASP.NET MVC Application

Step 2:
1.Create a table in the database by using Sql server express Local Db(if u have Sqlserver 2008/2012 u can create tables in those).
2.Creating table in LocalDb:
   Add Server file(.mdf file) in App_Start folder (right click on App_Start-->Add-->New Item--    >Choose "Data" on left side -->select Sql server database-->name it as "Search.mdf").
3.Adding Table:
   open server explorer-->expand Data Connections-->Expand Search.mdf-->right click tables folder--> Add New table.
Then table designer loads and create table with name it as Employee .

Searching in ASP.NET MVC Application
then click on update-->in new window click on Update database button then table created.

Searching in ASP.NET MVC Application

Step 3:
1.Create model classes using ADO.NET Entity Model
right click on models folder-->Add-->New Item-->Choose Data from left side-->select ADO.NET Entity Data Model-->name it Model.edmx-->click Add button.

Searching in ASP.NET MVC Application

2.choose Model from database

Searching in ASP.NET MVC Application

3.select Search.mdf in dropdown and name the connection string below.

Searching in ASP.NET MVC Application

4.Select the version of Entity framework here

Searching in ASP.NET MVC Application

5.select the table from the Database and click Finish.

Searching in ASP.NET MVC Application

6.Edmx file created with model class and context class as shown and don't worry about the other files in the folder..

Searching in ASP.NET MVC Application

Step 4: Now it's time to create a controller right click controller folder-->Add-->Controller-->name it EmployeeController.(Just build the solution once for scaffolding.)
1.Select MVC5 Controller with View,using Entity framework.

Searching in ASP.NET MVC Application

2.Select Model and context class

Searching in ASP.NET MVC Application

3.Click on Add then visual studio automatically creates all the Controller action methods and Corresponding Views as shown below.
Searching in ASP.NET MVC Application

4.Controller code is as follows
EmployeeController.cs:

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using Searchinginmvc.Models;

namespace Searchinginmvc.Controllers
{
    public class employeesController : Controller
    {
        private SearchEntities db = new SearchEntities();

        // GET: employees
        public ActionResult Index()
        {
            return View(db.employees.ToList());
        }

        // GET: employees/Details/5
        public ActionResult Details(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            employee employee = db.employees.Find(id);
            if (employee == null)
            {
                return HttpNotFound();
            }
            return View(employee);
        }

        // GET: employees/Create
        public ActionResult Create()
        {
            return View();
        }

        // POST: employees/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include = "Id,Name,Address,Designation")] employee employee)
        {
            if (ModelState.IsValid)
            {
                db.employees.Add(employee);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(employee);
        }

        // GET: employees/Edit/5
        public ActionResult Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            employee employee = db.employees.Find(id);
            if (employee == null)
            {
                return HttpNotFound();
            }
            return View(employee);
        }

        // POST: employees/Edit/5
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit([Bind(Include = "Id,Name,Address,Designation")] employee employee)
        {
            if (ModelState.IsValid)
            {
                db.Entry(employee).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(employee);
        }

        // GET: employees/Delete/5
        public ActionResult Delete(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            employee employee = db.employees.Find(id);
            if (employee == null)
            {
                return HttpNotFound();
            }
            return View(employee);
        }

        // POST: employees/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(int id)
        {
            employee employee = db.employees.Find(id);
            db.employees.Remove(employee);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}

The output for the application is as follows (run the application using F5).

Searching in ASP.NET MVC Application

we got the above error "The resource can not be found".if u got this type of error go to the route.cs file.we need to configure the route config file before we run the application.do the following modifications in the route.cs file.

Searching in ASP.NET MVC Application

now again run the application once

Searching in ASP.NET MVC Application

Step 5:
1.Implement search functionality:
if we want to implement the search functionality we need to change the Index action method in the "employeesController".

Searching in ASP.NET MVC Application
2.Now modify the index.cshtml page also to add the search textbox and filter button.
index.cshtml:

<h2>Index</h2>

<p>
    @Html.ActionLink("Create New", "Create")
</p>
<p>
@using (Html.BeginForm()) {
   <p>Name: @Html.TextBox("searchstring")
    <input type="submit" value="Filter" /></p>
}
</p>

3.Now run the application using F5 and the output will be like this..

Searching in ASP.NET MVC Application
4.Now enter any name of the contact for ex: Raviteja and press Filter button then it will appear like this.now you can any Name in the data below.

Searching in ASP.NET MVC Application

5.And can also add another serch method using Dropdownlist

employeesController.cs:

public ActionResult Index(string searchstring,string designation)
      {
            //import all the contacts from db into 'contacts'variable
            //this expressions are written in LINQ(language integrated query)
            var contacts = from c in db.employees
                           select c;
            var DesigList = new List();
            var desigQuery = from d in db.employees
                              orderby d.Designation
                              select d.Designation;

            DesigList.AddRange(desigQuery.Distinct());
            ViewBag.Desig = new SelectList(DesigList);

            //filtering data based on search string..
            if (!String.IsNullOrEmpty(searchstring)) {
                contacts = contacts.Where(s => s.Name.Contains(searchstring));
            }
            if (!String.IsNullOrEmpty(designation)) {
                contacts = contacts.Where(x => x.Designation == designation);
            }

            return View(contacts);
        }

6.change the index.cshtml page also with following code

Searching in ASP.NET MVC Application
7.Run the application and check output by selecting on the value from Dropdownlist like below.

Searching in ASP.NET MVC Application

You can check the output by giving another values also..

Download the code for this post: click here
Note: This code for reference only.My sincere advice is 'try a new application on your own it will help full for you to learn subject'.

I hope you enjoyed and learned how searching functionality is implemented.if you have any doubts please ask me i am always ready to help you..

0 comments:

Post a Comment