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
ViewData
dictionary 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
ViewData
dictionary 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
ViewData
dictionary can store any type of data, including strings, numbers, objects, and collections. However, sinceViewData
is 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
ViewData
to pass data to a partial view. In this case, you can set theViewData
dictionary 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.