Thursday, 16 June 2016

Different Ways to Pass Data to Partial View

Partial views are just Views which you can reuse across your ASP.NET MVC application. If you are from ASP.NET Web Forms background, you can think of Partial View as User Control. Partial views can contain anything – HTML elements for displaying the data or getting the input from the users. In this tip, we are going to see the different ways to pass data to partial view for displaying data to the partial view.

1. Pass Data from Enclosing View to Partial View

@{
   ViewBag.Title = "Index";
   double piValue = 3.14;
}

<h2>Index</h2>
@Html.Partial("_MyPartial", piValue)

In the partial view (_MyPartial.cshtml), I can consume the passed variable value by accessing @Model variable.
Data received is: @Model

2. Pass Data to Partial View using ViewBag/ViewData

 in the below Index action method, I am passing the piValue value from action method to the View.


        public ActionResult Index()
        {
            ViewBag.piValue = 3.14;
            return View();
        }

 In the View(Index.cshtml), I am passing the piValue to the partial view. 


@{
   ViewBag.Title = "Index";
}
<h2>Index</h2>
@Html.Partial("_MyPartial", (double) @ViewBag.piValue)

3. Pass Data to Partial View using Strongly Typed Model

 I have created instance of this class and pass it to the View. In the real world, we would be getting the value from database. 

    public ActionResult Index()
      {
            //Assume we are getting below data from the database
        var model = new Employee { Name = "John", Location = "New York" };
        return View(model);
      }

we can just use Modelkeyword to pass the data to the Partial View.


@model PassingData.Models.Employee

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

@Html.Partial("_MyPartial",Model)

4. Pass Data to Partial View using ViewData Dictionary

@{
    Html.RenderPartial("_CreateEditDisplay", Model, new ViewDataDictionary { { "Submit", true }, { "Action", "Edit" }, { "ReadOnly", false } });
}

Another Way -

@{
    Html.ViewData.Add(new KeyValuePair&lt;string, object&gt;("Submit", true));
    Html.ViewData.Add(new KeyValuePair&lt;string, object&gt;("Action", "Edit"));
    Html.ViewData.Add(new KeyValuePair&lt;string, object&gt;("ReadOnly", false));

    Html.RenderPartial("_CreateEditDisplay", Model, Html.ViewData);
}

Continue Reading →

Topics

ADO .Net (2) Ajax (1) Angular Js (17) Angular2 (24) ASP .Net (14) Azure (1) Breeze.js (1) C# (49) CloudComputing (1) CMS (1) CSS (2) Design_Pattern (3) DI (3) Dotnet (21) Entity Framework (3) ExpressJS (4) Html (3) IIS (1) Javascript (6) Jquery (9) Lamda (3) Linq (11) Mongodb (1) MVC (48) NodeJS (7) RDLC (1) Report (1) Sql Server (29) SSIS (3) SSRS (2) UI (1) WCF (12) Web Api (10) Web Service (1) XMl (1)