ViewData in MVC

ViewData is similar to ViewBag. We use to  transfer the data from Controller to View.

ViewData is a dictionary which can contain key-value pairs where each key must be string.

The following figure illustrates the ViewData.

ViewData only transfers data from controller to view, not vice-versa and It is valid only during the current request.

The following example demonstrates how to transfer data from controller to view using ViewData.

Example: ViewData in Action method

public ActionResult Index()
{
    IList<Student> studentList = new List<Student>();
    studentList.Add(new Student(){ StudentName = "Bill" });
    studentList.Add(new Student(){ StudentName = "Steve" });
    studentList.Add(new Student(){ StudentName = "Ram" });

    ViewData["students"] = studentList;
  
    return View();
}

In the above example, we have added a student list with the key “students” in the ViewData dictionary. So now, the student list can be accessed in a view as shown below.

Example: Access ViewData in a Razor View

<ul>
@foreach (var std in ViewData["students"] as IList<Student>)
{
    <li>
        @std.StudentName
    </li>
}
</ul>

Notice that we need to cast  the ViewData values to the appropriate data type.

We can also add a KeyValuePair into ViewData as shown below.

Example: Adding KeyValuePair in ViewData

public ActionResult Index()
{
    ViewData.Add("Id", 1);
    ViewData.Add(new KeyValuePair<string, object>("Name", "Bill"));
    ViewData.Add(new KeyValuePair<string, object>("Age", 20));

    return View();
}

ViewData and ViewBag both use the same dictionary internally. So we cannot have ViewData Key matches with the property name of ViewBag, otherwise it will throw a runtime exception.

Example: ViewBag and ViewData

public ActionResult Index()
{
    ViewBag.Id = 1;

    ViewData.Add("Id", 1); // throw runtime exception as it already has "Id" key
    ViewData.Add(new KeyValuePair<string, object>("Name", "Bill"));
    ViewData.Add(new KeyValuePair<string, object>("Age", 20));

    return View();
}

ViewBag in ASP.NET MVC

ViewBag is useful to transfer temporary data (which is not included in model) from the controller to the view. The viewBag is a  dynamic type property of ControllerBase class which is the base class of all the controllers.

The following figure illustrates the ViewBag.

In the above figure, it attaches Name property to ViewBag with the dot notation and assigns a string value to “Bill” to it in the controller. This can be accessed in the view like @ViewBag.Name. (@ is razor syntax to access the server side variable.)

You can assign any number of properties and values to ViewBag. If you assign the same property name multiple times to ViewBag, then it will only consider last value assigned to the property.

 

The following example demonstrates how to transfer data from controller to view using ViewBag.

Example: Set ViewBag in Action method

namespace MVC_BasicTutorials.Controllers
{
    public class StudentController : Controller
    {
        IList<Student> studentList = new List<Student>() { 
                    new Student(){ StudentID=1, StudentName="Steve", Age = 21 },
                    new Student(){ StudentID=2, StudentName="Bill", Age = 25 },
                    new Student(){ StudentID=3, StudentName="Ram", Age = 20 },
                    new Student(){ StudentID=4, StudentName="Ron", Age = 31 },
                    new Student(){ StudentID=5, StudentName="Rob", Age = 19 }
                };
        // GET: Student
        public ActionResult Index()
        {
            ViewBag.TotalStudents = studentList.Count();

            return View();
        }

    }
}

In the above example, we want to display the total number of students in a view for the demo. So, we have attached the TotalStudents property to the ViewBag and assigned the student count using studentList.Count().

Now, in the Index.cshtml view, you can access ViewBag.TotalStudents property and display all the student info as shown below.

Example: Acess ViewBag in a View

<label>Total Students:</label>  @ViewBag.TotalStudents

Output:

Total Students: 5

ViewBag doesn’t require typecasting while retriving values from it.

Internally, ViewBag is a wrapper around ViewData. It will throw a runtime exception, if the ViewBag property name matches with the key of ViewData.

Partial Views in MVC

Partial View:

In this section you will learn about partial views in ASP.NET MVC.

What is Partial View?

Partial view is a reusable view, which can be used as a child view in multiple other views. It eliminates duplicate coding by reusing same partial view in multiple places. You can use the partial view in the layout view, as well as other content views.

To start with, let’s create a simple partial view for the following navigation bar for demo purposes. We will create a partial view for it, so that we can use the same navigation bar in multiple layout views without rewriting the same code everywhere.

sample partial view
Partial View

The following figure shows the html code for the above navigation bar. We will cut and paste this code in a seperate partial view for demo purposes.

Partial Views

Create New Partial View:

To create a partial view, right click on Shared folder -> select Add -> click on View..

Note :If a partial view will be shared with multiple views of different controller folder then create it in the Shared folder, otherwise you can create the partial view in the same folder where it is going to be used.

In the Add View dialogue, enter View name and select “Create as a partial view” checkbox and click Add.

Partial Views

We are not going to use any model for this partial view, so keep the Template dropdown as Empty (without model) and click Add. This will create an empty partial view in Shared folder.

Now, you can cut the above code for navigation bar and paste it in _HeaderNavBar.cshtml as shown below:

Partial View: _HeaderNavBar.cshtml
<div class="navbar navbar-inverse navbar-fixed-top">
    <div class="container">
        <div class="navbar-header">
            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>
            @Html.ActionLink("Application name", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
        </div>
        <div class="navbar-collapse collapse">
            <ul class="nav navbar-nav">
                <li>@Html.ActionLink("Home", "Index", "Home")</li>
                <li>@Html.ActionLink("About", "About", "Home")</li>
                <li>@Html.ActionLink("Contact", "Contact", "Home")</li>
            </ul>
        </div>
    </div>
</div>

Thus, you can create a new partial view. Let’s see how to render partial view.

Render Partial View:

You can render the partial view in the parent view using html helper methods: Partial() or RenderPartial() or RenderAction(). Each method serves different purposes. Let’s have an overview of each method and then see how to render partial view using these methods.

Html.Partial():

@Html.Partial() helper method renders the specified partial view. It accept partial view name as a string parameter and returns MvcHtmlString. It returns html string so you have a chance of modifing the html before rendering.

The following table lists overloads of the Partial helper method:

Helper Method Description
MvcHtmlString Html.Partial(string partialViewName) Renders the given partial view content in the referred view.
MvcHtmlString Html.Partial(string partialViewName,object model) Renders the partial view content in the referred view. Model parameter passes the model object to the partial view.
MvcHtmlString Html.Partial(string partialViewName, ViewDataDictionary viewData) Renders the partial view content in the referred view. View data parameter passes view data dictionary to the partial view.
MvcHtmlString Html.Partial(string partialViewName,object model, ViewDataDictionary viewData) Renders the partial view content in the referred view. Model parameter passes the model object and View data passes view data dictionary to the partial view.

Html.RenderPartial():

The RenderPartial helper method is same as the Partial method except that it returns void and writes resulted html of a specified partial view into a http response stream directly.

Helper method Description
RenderPartial(String partialViewName) Renders the specified partial view
RenderPartial(String partialViewName, Object model) Renders the specified partial view and set the specified model object
RenderPartial(String partialViewName, ViewDataDictionary viewData) Renders the specified partial view, replacing its ViewData property with the specified ViewDataDictionary object.
RenderPartial(String partialViewName, Object model, ViewDataDictionary viewData) Renders the specified partial view, replacing the partial view’s ViewData property with the specified ViewDataDictionary object and set the specified model object

Html.RenderAction():

The RenderAction helper method invokes a specified controller and action and renders the result as a partial view. The specified Action method should return PartialViewResult using the Partial() method.

Name Description
RenderAction(String actionName) Invokes the specified child action method and renders the result in the parent view.
RenderAction(String actionName, Object routeValue) Invokes the specified child action method using the specified parameters and renders the result inline in the parent view.
RenderAction(String actionName, String controllerName) Invokes the specified child action method using the specified controller name and renders the result inline in the parent view.
RenderAction(String actionName, RouteValueDictionary routeValues) Invokes the specified child action method using the specified parameters and renders the result inline in the parent view.
RenderAction(String actionName, String controllerName, Object routeValue) Invokes the specified child action method using the specified parameters and controller name and renders the result inline in the parent view.
RenderAction(String actionName, String controllerName, RouteValueDictionary routeValues) Invokes the specified child action method using the specified parameters and controller name and renders the result inline in the parent view.

So now, we can use any of the above rending methods to render the _HeaderNavBar partial view into _Layout.cshtml. The following layout view renders partial view using the RenderPartial() method.

Example: Html.RenderPartial()
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>@ViewBag.Title - My ASP.NET Application</title>
    @Styles.Render("~/Content/css") 
    @Scripts.Render("~/bundles/modernizr")
</head>
<body>
    @{
        Html.RenderPartial("_HeaderNavBar");   
    }
    <div class="container body-content">
        @RenderBody()
        
        <hr />
        <footer>
            <p>&copy; @DateTime.Now.Year - My ASP.NET Application</p>
        </footer>
    </div>

    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/bootstrap")
    @RenderSection("scripts", required: false)
</body>
</html>

 

Note :RenderPartial returns void, so a semicolon is required at the end and so it must be enclosed in the braces.

The following layout view uses the Partial method to render partial view_HeaderNavBar.cshtml.

Example: Html.Partial()
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>@ViewBag.Title - My ASP.NET Application</title>
    @Styles.Render("~/Content/css") 
    @Scripts.Render("~/bundles/modernizr")
</head>
<body>
     @Html.Partial("_HeaderNavBar")   
    <div class="container body-content">
        @RenderBody()
        
        <hr />
        <footer>
            <p>&copy; @DateTime.Now.Year - My ASP.NET Application</p>
        </footer>
    </div>

    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/bootstrap")
    @RenderSection("scripts", required: false)
</body>
</html>

 

Note :@Html.Partial() method doesn’t need to be in code block because it returns a html string.

You will see following UI in browser when you run the application.

Index.cshtml

New Features in .Net framework 4.5 and 5.0

Explaining the following features:

  • Parallel foreach
  • BigInteger
  • Expando Objects
  • Named and Optional Parameters
  • Tuple

1. Parallel.ForEach

Parallel.ForEach is a feature introduced by the Task Parallel Library (TPL). This feature helps you run your loop in parallel. You need to have a multi-processor to use of this feature.

Simple foreach loop

foreach (string i in listStrings)

{

……….

}

Parallel foreach

Parallel.Foreach(listStrings, text=>
{
……………………..
});

2. BigInteger

BigInteger is added as a new feature in the System.Numerics DLL. It is an immutable type that represents a very large integer whose value has no upper or lower bounds.

BigInteger obj = new BigInteger(“123456789123456789123456789”);

3. ExpandoObject

The ExpandoObject is part of the Dynamic Language Runtime (DLR). One can add and remove members from this object at run time.

Create a dynamic instance.

dynamic Person = new ExpandoObject();

Person.ID = 1001;

Person.Name = “Princy”;

Person.LastName = “Gupta”;

4. Named and Optional Parameters

Optional Parameters

A developer can now have some optional parameters by providing default values for them. PFB how to create optional parameters.

Void PrintName(string a, string b, string c = “princy”)

{

Console.Writeline(a, b, c)

}

We can now call the function PrinctName() by passing either two or three parameters as in the following:

PrintName(“Princy”,”Gupta”,”Jain”);
PrinctName(“Princy”,”Gupta”);

Output

PrincyGuptaJain
PrincyGuptaprincy

Note: An optional parameter can only be at the end of the parameter list.

Named Parameters

With this new feature the developer can pass values to parameters by referring to parameters by names.

Void PrintName(string A, string B

{

}

Function call

PrintName (B: “Gupta”, A: “Princy”);

With this feature we don’t need to pass parameters in the same order to a function.

5. Tuple

A Tuple provides us the ability to store various types in a single object.

The following shows how to create a tuple.

Tuple<int, string, bool> tuple = new Tuple<int, string, bool>(1,”princy”, true);

Var tupleobj = Tuple.Create(1, “Princy”, true);

In order to access the data inside the tuple, use the following:

string name = tupleobj.Item2;

int age = tupleobj.Item1;

bool obj = tupleobj.Item3;