How to pass list of string from Controller to view in MVC

Introduction

In my previous post i have been learned about pass data from controller to view in MVC. This post contains a list of string value in controller action method and we want to pass that value to MVC View.

lets take a simple Example.

Step-1 : Create a List<String> collection and pass these collection to Dynamic property of ViewBag object.
Step-2: Return View in Controller Index method.
Step-3: Create a view and access dynamic property of ViewBag Object from Controller Index method.

Controller class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MvcApplication4.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/

        public ActionResult Index()
        {
            ViewBag.country = new List<string>()
            {
                "USA",
                "INDIA",
                "UK"
            };
            return View();
        }

    }

}

View
@{
    ViewBag.Title = "List of string value";
}


<h2>Country List</h2>
<ul>
    @foreach (string  country in ViewBag .country)
    {
        <li>@country</li>
    }




</ul>
Output
How to pass list of string from Controller to view in MVC

How to pass list of string from Controller to view in MVC How to pass list of string from Controller to view in MVC Reviewed by Jacob Lefore on October 09, 2013 Rating: 5

No comments