viewdata in asp.net mvc
ViewData is a dictionary-like object that is available in ASP.NET MVC views and can be used to pass data from the controller to the view.
Here's how to use ViewData in ASP.NET MVC:
- In the controller, add the data you want to pass to the
ViewDatadictionary using a key-value pair. For example:
public ActionResult MyAction()
{
ViewData["Title"] = "My Page Title";
ViewData["Message"] = "Welcome to my page!";
return View();
}
- In the view, you can access the data stored in the
ViewDatadictionary by using the key as an index. For example:
@{
ViewData["Title"] = "My Page Title";
ViewData["Message"] = "Welcome to my page!";
}
# @ViewData["Title"]
<p>@ViewData["Message"]</p>
The
ViewDatadictionary can store any type of data, including strings, numbers, objects, and collections. However, sinceViewDatais a dictionary-like object, it does not provide compile-time checking, so you need to be careful when accessing its keys to avoid runtime errors.You can also use
ViewDatato pass data to a partial view. In this case, you can set theViewDatadictionary in the parent view or in the controller action that returns the partial view. For example:
@{
ViewData["Title"] = "My Page Title";
ViewData["Message"] = "Welcome to my page!";
}
<div>
@Html.Partial("_MyPartial")
</div>
In the partial view:
## @ViewData["Title"] <p>@ViewData["Message"]</p>
ViewData can be a useful way to pass data between the controller and view, especially for small amounts of data that do not require a strongly-typed model. However, for larger amounts of data or for data that requires more complex manipulation, it is often better to use a strongly-typed model or a view model.
