Transferred from: http://www.cnblogs.com/gaopin/archive/2012/11/13/2767515.html
Controller to view value ViewData detailed
1. Passing a string to the view
In action we save the string in ViewData (or viewbag [ASP. NET 3 or above]) with the following code:
Public ActionResult Index ()
{
viewdata["str1"]= "This is a string";
You can also use ViewBag to pass values
Viewbag.str2= "This is another string";
return View ();
}
In the view we can use the following code to display the string
2. Passing a collection of strings to the view
Public ActionResult Index ()
{
list<string> str1= new list<string> ();
Str1. ADD ("1111");
Str1. ADD ("2222");
Str1. ADD ("3333");
viewdata["str"] = STR1;
return View ();
}
In the view we display the value of the STR1 by using the following statement
@foreach (var A in viewdata["str"] as list<string>)
{
@a
}
3. Passing the value of a DataTable to the view
Public ActionResult Index ()
{
DataTable newtable = new DataTable ("D");
NewTable. Columns.Add ("Product number", typeof (String));
NewTable. Columns.Add ("Customer number", typeof (String));
DataRow NewRow = newtable. NewRow ();
newrow["Product number"] = "132323213434";
newrow["customer number"] = "344223443244";
NewTable. Rows.Add (NewRow);
DataRow Snewrow = newtable. NewRow ();
snewrow["Product number"] = "343432445456";
snewrow["customer number"] = "454523432453";
NewTable. Rows.Add (Snewrow);
viewdata["DT"]= newtable;
return View ();
}
In the view we display the value of DT by the following statement
Note: At the top of the first add: @using System.Data;
<ul>
@foreach (DataRow Dr in (viewdata["DT"] as DataTable). Rows)
{
<li>
@dr ["Product number"], @dr ["Customer number"],
</li>
}
</ul>