Codechef4u is a community for computer professionals,by computer professionals,just like you; who loves sharing and helping each others,Join them
Share your post

A partial view

Introduction:

In asp.net Web form naturally we create reusable components using asp.net user controls (i.e. UserDetail.ascx) or web server controls.

With MVC model for same purpose we use partial view. While ASP.NET MVC partial views may behave similarly in theory to web user controls, syntactically and functionally, the two behave differently.

Asp.net user control supports view state, post backs and events while MVC partial views do not use any of these techniques.

Partial view description:

A partial view enables you to define a view that will be rendered inside a parent view. When a partial view is instantiated, it gets its own copy of the ViewDataDictionary object that is available to the parent view.

HTML helper provides an extension method called Html.Partial to render partial views. Below explained different flavors of Partial method:

a.  @Html.Partial(string partialViewName):Renders the given partial view content into the referred view.
b.   @Html.Partial(string partialViewName,object model):Renders the partial view content into the referred view. Model parameter passes the model object to the partial view.
c.  @Html.Partial(string partialViewName, ViewDataDictionary viewData):Renders the partial view content into the referred view. View data parameter passes view data dictionary to the partial view.
d.  @Html.Partial(string partialViewName,object model, ViewDataDictionary viewData): Renders the partial view content into the referred view. Model parameter passes the model object and View data passes view data dictionary to the partial view.

Points to remember:

 1. Partial view has access to parent view data.
 2. If you update partial view, those updates affect only the partial view's ViewData object.
 3. View state is not supported in partial view.
 4. @Html.Partial() HTML helper renders the given partial view into the current view.

 

Example:

Create partial view:

To create a partial view, right click the /Views/Shared folder > Add > View. Type a View Name, type or choose a class from the Model class and check the Create as a partial view option, as shown below


Click Add and a partial view file at Views/Shared/UserLeaveSummery.cshtml gets created.


Inserting Partial Views into parent view:

Parent view (Index.cshtml)

@model System.Collections.Generic.List<BlogProj.Models.ViewModel.ViewLeaveDetails>
 
@using System.Web.Mvc.Html
@{
    ViewBag.Title = "Home Page";
}
 
<div style="height:25px"></div>
<h2>@ViewBag.Message</h2>
 
<div><p>here parent view data you can add other logic </p>
 </div>
<div>
 <p>partial view called </p>
    @Html.Partial("~/Views/shared/UserLeaveSummery.cshtml",Model)
</div>

 

Partial view (UserLeaveSummery.cshtml):

@model System.Collections.Generic.List<BlogProj.Models.ViewModel.ViewLeaveDetails>
 
 <table class="ui-widget-content" style="border-spacing:0px;font-size:15px; font-family:Verdana">
 
    <tr class="ui-widget-header">
        
         <th>
         Type
        </th>
            <th>
         Remaining
        </th>
          <th>
         Approved
        </th>
         <th>
         Pending
        </th>
 
    </tr>
         
@foreach (var item in Model)
{
    <tr>
  
       <td>
          @Html.DisplayFor(modelItem=> item.Leavetype)
         
        </td>
        <td style="text-align:center">
            @Html.DisplayFor(modelItem=> item.RemainingLeaves)
        </td>
 
         <td style="text-align:center">
            @Html.DisplayFor(modelItem=> item.ApprovedLeaves)
        </td>
        <td style="text-align:center">
            @Html.DisplayFor(modelItem=> item.PendingForApprovel)
        </td>
       
   </tr>
}
 
</table>
    


Model:

public class ViewLeaveDetails
    {
        public string Leavetype { get; set; }
        public int LeavetypeId { get; set; }
        public int RemainingLeaves { get; set; }
        public int ApprovedLeaves { get; set; }
        public int PendingForApprovel { get; set; }
    }


Home Controller Action (Index event returns partial view model data):

private UnituOfWork unitOfWork = new UnituOfWork();
        public ActionResult Index()
        {
            var LeavesDetail =unitOfWork.LeaveDetails(GetUser());
            ViewBag.Message = " Welcome to Easy Leave HR solution";
 
            return View(LeavesDetail);
        }
 
        public Guid GetUser()
        {
            MembershipUser user = Membership.GetUser(HttpContext.User.Identity.Name);
            Guid userid = (Guid)user.ProviderUserKey;
 
            return userid;
        }

 

DLL Method returns leave details:

        public List<ViewLeaveDetails> LeaveDetails(Guid userId)
        {
            List<ViewLeaveDetails> Details = new List<ViewLeaveDetails>();
            using (ApplicationServices BlogDbContext = new ApplicationServices())
            {
                using (var con = new SqlConnection(BlogDbContext.Database.Connection.ConnectionString))
                {
                    // var con = (SqlConnection)BlogDbContext.Database.Connection;
                    con.Open();
                    using (SqlCommand storedProcCommand =
                    new SqlCommand("LeaveDetails", con))
                    {
                        storedProcCommand.CommandType = CommandType.StoredProcedure;
                        storedProcCommand.Parameters.Add("@TotalLeaves", SqlDbType.Int);
                        //Uncomment this line to return the proper output value.
                        storedProcCommand.Parameters["@TotalLeaves"].Direction = ParameterDirection.Output;
                        storedProcCommand.Parameters.AddWithValue("@userId", userId);
                        var dr =
                            storedProcCommand.ExecuteReader();
                        var test = storedProcCommand.Parameters["@TotalLeaves"].Value;
                        while (dr.Read())
                        {
                            ViewLeaveDetails Detail = new ViewLeaveDetails();
                            if (dr["LeaveTitle"] != DBNull.Value)
                            {
                                Detail.Leavetype = (string)dr["LeaveTitle"];
                                Detail.LeavetypeId = (int)dr["LeaveTypeid"];
                                Detail.RemainingLeaves = (int)dr["Leaves"];
                                if (dr["PendingLeaves"] != DBNull.Value)
                                {
                                    Detail.PendingForApprovel = (int)dr["PendingLeaves"];
                                }
                                else
                                {
                                    Detail.PendingForApprovel = 0;
                                }
                                if (dr["ApprovedLeaves"] != DBNull.Value)
                                {
                                    Detail.ApprovedLeaves = (int)dr["ApprovedLeaves"];
                                }
                                else
                                {
                                    Detail.ApprovedLeaves = 0;
                                }
                            }
 
                            Details.Add(Detail);
                        }
                    }
 
                }
 
            }
            return Details;
        }
 

 

 

Invalid entry,please enter valid data.

Loading