Friday, July 11, 2014

Partial View in ASP.Net MVC 4

Partial View in ASP.Net MVC 4

In this blog, I am going to tell you how to make a partial view and render it on another view in asp.net mvc 4.

We can call the partial view in another view like:

@Html.RenderPartial("~/Views/Shared/_StudentPartialView.cshtml", student);

Or

@Html.Partial("~/Views/Shared/_StudentPartialView.cshtml", student);

In this example, I am going to extend my webgrid example so if want to learn the webgrid first then you can read my blog here:


Step -1

First create a table named “Student” in the database with the following fields:











And insert some dummy data in the table to show in the webgrid.

Step -2

Now create an asp.net mvc 4 web application and add a model class named “Student” and write the below code in it:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace WebGridMvcApp.Models
{
    public class Student
    {
        public string StudentId { get; set; }
        public string Name { get; set; }
        public string Age { get; set; }
        public string Address { get; set; }
        public string Course { get; set; }
    }

}

Step -3

Now add a controller to the project and named “HomeController” and write the below code in it:
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebGridMvcApp.Models;

namespace WebGridMvcApp.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/

        public ActionResult Index()
        {
            List<Student> student = new List<Student>();

            string ConnString = ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString;
            SqlConnection conn = new SqlConnection(ConnString);
            conn.Open();
            SqlCommand cmd = new SqlCommand("Select * From StudentInformation",conn);
            SqlDataReader reader = cmd.ExecuteReader();
            while (reader.Read())
            {
                student.Add(new Student {
                    StudentId = reader["StudentId"].ToString(),
                    Name = reader["Name"].ToString(),
                    Age = reader["Age"].ToString(),
                    Address = reader["Address"].ToString(),
                    Course = reader["Course"].ToString()

                });
            }

            return View(student);
        }

    }
}

Step -4

Now add a partial view to the project named “_StudentPartialView” and it will be strongly typed view like this:







































Now write the below code in the partial view:
@model WebGridMvcApp.Models.Student

@{
    Layout = null;
}


<!DOCTYPE html>

<html>
<head>
</head>
<body>
    <div >
        <div>
            <label>Name : </label>
            @Html.TextBoxFor(m=>m.Name)
        </div>
        <div>
            <label>Age : </label>
            @Html.TextBoxFor(m=>m.Age)
        </div>
        <div>
            <label>Address : </label>
            @Html.TextBoxFor(m=>m.Address)
        </div>
        <div>
            <label>Course : </label>
            @Html.TextBoxFor(m=>m.Course)
        </div>
    </div>
</body>
</html>

Step -5

Now create a normal view named “Index” and it will be strongly typed too like this:

@model IEnumerable<WebGridMvcApp.Models.Student>

@{
    Layout = null;
}


@{
   
    WebGridMvcApp.Models.Student student = new WebGridMvcApp.Models.Student();
   
    var grid = new WebGrid(Model, canPage: true, rowsPerPage: 10,
    selectionFieldName: "selectedRow", ajaxUpdateContainerId: "WebgridContent");
    grid.Pager(WebGridPagerModes.NextPrevious);
}


<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
    <style type="text/css">
    .webGrid { margin: 4px; border-collapse: collapse; width: 500pxbackground-color:#6ec0de;}
    .header { background-color: #C1D4E6; font-weight: bold; color: #FFF; }
    .webGrid th, .webGrid td { border: 1px solid #C0C0C0; padding: 5px; }
    .alt { background-color: #E4E9F5; color: #000; }
    .gridHead a:hover {text-decoration:underline;}
    .description { width:auto}
    .select{background-color: #71857C}
</style>
</head>
<body>
    <div>
        <div id="WebgridContent">
    @grid.GetHtml(tableStyle: "webGrid",
            headerStyle: "header",
            alternatingRowStyle: "alt",
            selectedRowStyle: "select",
            columns: grid.Columns(
            grid.Column("ID","StudentId", format: (item) => item.GetSelectLink(item.StudentId)),
            grid.Column("Name", "Name"),
            grid.Column("Age", "Age"),
            grid.Column("Address", "Address"),
            grid.Column("Course", "Course")
     ))
</div>

        <div>
            @if (grid.HasSelection)
            {
                student = (WebGridMvcApp.Models.Student)grid.Rows[grid.SelectedIndex].Value;
                Html.RenderPartial("~/Views/Shared/_StudentPartialView.cshtml", student);
            }
          
        </div>
    </div>
</body>

</html>


Output

Now build the application and run it:
















Click on id of the record and you can see that partial view is rendered in the view





















Thank you for reading this article, please put your valuable comment or any suggestion/question in the comment box. 









No comments:

Post a Comment