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.

Usage of BundleConfig.cs file with sample an example in MVC

Follow below steps:

Step-1:

To add Bundle config file, first you need to add the Microsoft.AspNet.Web.Optimization nuget package to your web project:

Install-Package Microsoft.AspNet.Web.Optimization

Step-2:

Then under the App_Start folder create a new cs file called BundleConfig.cs.

Add below code in Bundleconfig file;

namespace BundleConfigEx
{
public class BundleConfig
{
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new ScriptBundle(“~/bundles/sciptsJS”).Include(“~/Scripts/jquery-{version}.js”));
BundleTable.EnableOptimizations = true;
}
}

}

bundles.Add(new ScriptBundle(“~/bundles/sciptsJS”).Include(“~/Scripts/jquery-{version}.js”));

we will add number of bundles(Based on Our requirement) like above line of code. 

Step-3:

For this we will register our bundles in Global.asax.cs file like below;

BundleConfig.RegisterBundles(BundleTable.Bundles);

Step-4:

Now we can call this bundle in our _layout file (or) View(Index.cshtml) like below

@Scripts.Render(“~/bundles/sciptsJS”)

Insert data using Jquery Ajax Call in ASP.NET MVC

Follow below steps to Insert data into database using ajax call in MVC;

Step-1:

Create One table To Save data

Step-2: 

Create procedure to insert data like below

CREATE PROCEDURE [dbo].[InsertData]
(
@Address nvarchar(50),
@Name nvarchar(50)
)

AS
BEGIN
INSERT INTO Tbl_Test
(
Address
,Name
)
Values
(
@Address
,@Name
)
END

Step-3:

Create an MVC sample application to insert data

Step-4:

Create Model class in Models folder

Write following code in model class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace BundleConfigEx.Models
{
public class SaveData
{
public string Address { get; set; }
public string Name { get; set; }
}
}

Step-5:

Add controller class

paste below code in controller class

using BundleConfigEx.Models;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace BundleConfigEx.Controllers
{
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(SaveData objdata)
{
try
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings[“MyConnection”].ToString());
con.Open();
SqlCommand cmd = new SqlCommand(“USP_InsertData”, con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue(“@Address”, objdata.Address);
cmd.Parameters.AddWithValue(“@Name”, objdata.Name);
cmd.ExecuteNonQuery();
con.Close();

}
catch (Exception)
{

throw;
}
return View(“Index”);
}
}
}

Step-6:

Create a view and paste below code;

@model BundleConfigEx.Models.SaveData
@using System.Web.Optimization;

@{
ViewBag.Title = “Index”;
}

<h2>Index</h2>
<script src=”~/Scripts/jquery-1.10.2.js”></script>
<script src=”~/Scripts/jquery-1.10.2.min.js”></script>
<div>
<table>
<tr>
<td>Address</td>
<td>
<input type=”text” id=”txtaddress” />
</td>
</tr>
<tr>
<td>Name</td>
<td>
<input type=”text” id=”txtname” />
</td>
</tr>
<tr>
<td>
<input type=”button” id=”btnsubmit” value=”Save” />
</td>
</tr>
</table>

<script type=”text/javascript”>
$(document).ready(function () {
$(‘#btnsubmit’).click(function () {
$.ajax(
{
type: “POST”,
url: ‘Home/Index’,
data: {
Address: $(‘#txtaddress’).val(),
Name: $(‘#txtname’).val(),
}

});

});
});
</script>
</div>

All the best good luck 🙂