user3244721
user3244721

Reputation: 754

Display List in View in MVC

I have a List with has three values.I want to display in view.Here is my approach

My Controller Function


public List<Movie> Index()
    {
        Movie obj = new Movie();
       return obj.ShowData();
    }

My model class & Function

 Database db = DatabaseFactory.CreateDatabase("MyDBLINK");
    public int ID { get; set; }
    public string Title { get; set; }

 public List<Movie> GetData()
    {
        try
        {
            DbCommand dbCommand = db.GetStoredProcCommand("SP");

            DataSet dsResult = db.ExecuteDataSet(dbCommand);

            List<Movie> Prop = new System.Collections.Generic.List<Movie>();
            Prop = (from DataRow row in dsResult.Tables[0].Rows
                    select new Movie
                    {
                        ID = Convert.ToInt32(row["ID"].ToString()),
                        Title = row["Title"].ToString()
                    }).ToList();
            return Prop;
        }
        catch (Exception ex)
        {
            return null;
        }
    }

Here is my view

@model System.Collections.Generic.List<MvcFirst.Controllers.MoviesController>

 @foreach (var item in Model)
{
<ul>
    <li>@item.ID</li>
    <li>@item.Title</li>

</ul>
}

My Question is how to display this list in View? Secondly Is this approach is Good for CPU?

Upvotes: 0

Views: 2651

Answers (2)

Felipe Oriani
Felipe Oriani

Reputation: 38598

Everything looks almost fine, your controller should be something like this:

public ActionResult Index()
{
   var movie = new Movie();
   var result = movie.GetData(); // instance object and read the method to get the list
   return View(result);
}

An ActionResult could be any type of result, a View, a File to download, a Javascript, A StyleSheet, etc... but normaly is a View with the same name of action. If your action method is called Index, asp.net mvc will search for a View called Index on the Views folder. The part return View(result); means you are returning this View and passing the result object as a Model to your View.

Your View should be strogly typed with the entity (because you are returning it from the controller), not the controller:

@model System.Collections.Generic.List<Movie>

@foreach (var item in Model)
{
<ul>
    <li>@item.ID</li>
    <li>@item.Title</li>    
</ul>
}

Upvotes: 1

peterthegreat
peterthegreat

Reputation: 406

I think you've missunderstood how Controllers and Views work. Your Index() method need to return an ActionResult which will generate your view and return it to the user.

//My Controller Function

public ActionResult Index()
{
    Movie obj = new Movie();
    return View(obj.GetData()); //This will take the view with the same name as your method (Index in this case) and return it to the client/browser.
}

I hope I understood you question correctly.

Edit: I forgot to make the view stronly typed as Felipe Oriani has showned you

Upvotes: 0

Related Questions