Sunday 14 October 2012

MVC - C# - Simple Example how to pass parameters from controller to view

Watch this example on YouTube


or follow these instructions:
Create the following function in your controller class

        public ActionResult PassValueFromControllerToView(string text, int numb = 10)
        {
            ViewBag.Text = text;
            ViewBag.Numb = numb;
            return View();
        }
This function receives string and number, if number is not passed, it will be defaulted to 10.
Next, right click somewhere inside the class and select Add View...

Click Add
Add the following code:
<b>Display string that was passed to function for number of times - by defult 10</b>
<ul>
    @for (int i = 0; i < ViewBag.Numb; i++){
        <li>
            @ViewBag.Text;
        </li>
    }
</ul>
Now when you run the program and navigate to controller name(in my case it is called user), function name  http://localhost:51480/user/PassValueFromControllerToView?text=this is my text&numb=4

The following screen will be displayed


If I don't pass any number, it will default to 10
http://localhost:51480/user/PassValueFromControllerToView?text=this is my text

No comments:

Post a Comment