ASP. NET MVC ViewData usage

Source: Internet
Author: User

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>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.