Sunday, February 01, 2015

MVC Basics 01 (viewbag)

Started to resume learning MVC lately, overall its clean, feels nice as compared to Web.Form, here are some basics to share

1. Passing Data from Controller to Views. (using viewbag)


    public ActionResult Index()
        {
            List<selectlistitem> color = new List<selectlistitem>();
            color.Add(new SelectListItem { Text = "red", Value = "1" });
            color.Add(new SelectListItem { Text = "blue", Value = "2" });
            color.Add(new SelectListItem { Text = "green", Value = "3" });
            ViewBag.Colors = color;
            ViewBag.Time = DateTime.Now.ToString("dd/MM/yyyy hh:mm");
            return View();
        }

in Controller, use @ViewBag to get access to the passed data

    <div>
        <p>Message from Viewbag @ViewBag.Time</p>
        <div class="panel">
            <div class="panel panel-heading"><h1>List from Controller</h1></div>
            <div class="panel panel-body">
                Select a Color from viewbag @Html.DropDownList("Colors")
            </div>
            <div class="panel-body">
                <div class="btn btn-default">@Html.ActionLink("Back to Main Index","Index","Home")</div>
           </div>
        </div>
    </div>

No comments: