What is ViewData In ASP.NET MVC ?

In ASP.NET MVC there are lots of techniques to pass data between requests for temporary purposes unlike session variable which will hold the value throughout the application and consume the server resources unnecessarily which is not required.
So  in this article we will learn about ViewData in short and useful description which will understandable for beginners as well as students .before proceeding please read previous articles for better understanding.
What is ViewData?
ViewData is used to pass data from controller to view for single request which holds the data in key-value pairs were key will be string type and value is object type.


Key points
  • Used to pass data from controller to view. 
  • ViewData is the object of ViewDataDictionary class which holds the data by key and value pair. 
  • In ViewData Key is the string type and value is the object type .
  • We need to handle null otherwise if ViewData value is null and we tried to access value then it throws the exception.
  • The value assigned to ViewData is only available for single request, if redirection happens then value will be null.
  • It is  property of ControllerBase class.
  •  It’s  require type conversion such as int to string or string to int etc .
Example
There are two ways to declare or assign the value to the ViewData which are as follows
Write the following code into your controller class
Method :1
//Assigning value to ViewData
 ViewData["City"] = "Mumbai";
In the above code City is the key and Mumbai is the value for ViewData object.
Accessing ViewData value in View
<div>
@ViewData["City"]
</div>
In the above way we can access the ViewData value into the view.
Method :2
//Assigning value to ViewData
  ViewData.Add("Name", "Vithal Wadje");
In the above code City is the key and Mumbai is the value for ViewData object.
Accessing ViewData value in View
<div>
@ViewData["Name"]
</div>
In the above way we can access the ViewData value into the view.
Summary
I hope this article is useful for all readers . If you have a suggestion related to this article then please contact me.
Related Article .

Post a Comment

www.CodeNirvana.in

Protected by Copyscape Online Copyright Protection
Copyright © Compile Mode