A day with .Net

My day to day experince in .net

Partial Page Rendering 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();
            if (Request.IsAjaxRequest())
            {
                return PartialView("_Movie", movies);
            }
            return View(movies);
        }
              
    }

3. Update the Razor of Index.cshtml as

@model IEnumerable<Learan.Models.Movie>
<h3>
    Move Search By year</h3>
@using (
    Ajax.BeginForm("Index", "Home", new AjaxOptions { HttpMethod = "GET", UpdateTargetId = "MovieTable" }))
{
    <input id="SearchBox" type="text" name="query" />
    <input id="submit" type="submit" />
}
<div id="MovieTable">
    @Html.Partial("_Movie", Model)
</div>

4. Create the partial view _Movie.cshtml

@model IEnumerable<Learan.Models.Movie>

<p>
   Movie List
</p>
<table>
    <tr>
        <th>Title</th>
        <th>Year</th>
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.Encode(item.Title)
        </td>
         <td>
            @Html.Encode(item.ReleaseYear)
        </td>
    </tr>
}

</table>
Advertisements

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s