Pages

Thursday, April 7, 2011

Passing value from Controller to HTML controls in Views in ASP.NET MVC2,0

This blog explains how to pass a value from Controller to the html controls used in Views.

For temporary storage we use ViewData["name"] or TempData["name"]. In controller the values are stored in one of these temporary storages, and the views could read the values and finally typecasted to the html control's value type and then binded to the control.

Example:
Consider we need to pass value to an textbox.

in controller we give
ViewData["TextBox"] = "Textbox value";
in View we give :
< %= Html.TextBox("txtBox", ViewData["TextBox"].ToString())% >

In case of dropdowlist or listbox - need to typecast as (IEnumerable)ViewData["name"] .. and while storing to the view data - need to store a list of values.

No comments:

Post a Comment