C3rd
HowTo: Access Controller method/function from a View
Posted: 20 Dec 2012, 11:32am - ThursdayI've been wondering how to access the controller method/function from a View. I found a solution from Jeffrey Palermo which he explain it in details. Though, my case that I want to happen is about random numbers. Controller Codes:
public ActionResult Welcome(string name, int num = 1) { ViewBag.Message = "Hello " + name; ViewBag.Num = num; ViewBag.GetRandom = new Func<int, int, int>(getRandomNumber); return View(); } private int getRandomNumber(int min, int max) { Random rand = new Random(); return rand.Next(min, max); }View Codes:
<ul> @for (int i = 0; i < ViewBag.GetRandom(3, 100); i++) { <li>@ViewBag.Message</li> } </ul>or...
@{ ViewBag.Num = ViewBag.GetRandom(3, 100); } <h2>Welcome</h2> Generated Random Number: @ViewBag.Num <ul> @for (int i = 0; i < ViewBag.Num; i++) { <li>@ViewBag.Message</li> } </ul>One thing that confusing about this sample codes is; During the method declaration from the Controller, you use the new Func<>(method_name) -- the first int from <> is the minimum value, 2nd int is the maximum value and the third value is the return value.