A day with .Net

My day to day experince in .net

Implement a search box using MVC 4

Posted by vivekcek on May 27, 2013

1. Create a model

public class Movie
        private string _title;

        public string Title
            get { return _title; }
            set { _title = value; }
        private int _releaseYear;

        public int ReleaseYear
            get { return _releaseYear; }
            set { _releaseYear = value; }

2. Implement the home controllers Index action as given below.

public class HomeController : Controller
        public ActionResult Index(string query)
            List<Movie> Movies = new List<Movie> {new Movie(){ Title="Transformer", ReleaseYear=2008},
            new Movie(){ Title="Titanic", ReleaseYear=2008},
            new Movie(){ Title="Predator", ReleaseYear=2008},
            new Movie(){ Title="Men in blck", ReleaseYear=2008},
            new Movie(){ Title="Terminator", ReleaseYear=2009},
            new Movie(){ Title="Indiana jones", ReleaseYear=2009},
            new Movie(){ Title="Life is beautiful", ReleaseYear=2009},
            new Movie(){ Title="jurasic park", ReleaseYear=2007},
            new Movie(){ Title="Luck", ReleaseYear=2007},
            var movies=Movies.Where(x=>x.ReleaseYear==(Convert.ToInt32(query))||query==null).ToList();
            return View(movies);

3. Update the Razor of Index.cshtml as

@model IEnumerable<Learan.Models.Movie>

    Move Search By year</h3>
@using (
    Html.BeginForm("Index", "Home"))
    <input id="SearchBox" type="text" name="query" />
    <input id="submit" type="submit" />

<div id="MovieTable">

4. Create the partial view _Movie.cshtml

@model IEnumerable<Learan.Models.Movie>

   Movie List

@foreach (var item in Model) {


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s