Goober
Goober

Reputation: 13508

C# ASP.Net MVC View Issue

I have an interface that contains a single method called ListAll()

using System.Collections.Generic;
namespace MvcApplication1.Models
{
public interface IMovieRepository
{
IList<Movie> ListAll();
}
}

I have a class that implements that interface:

namespace MvcApplication1.Models
{
public class MovieRepository : IMovieRepository
{
private MovieDataContext _dataContext;
public MovieRepository()
{
_dataContext = new MovieDataContext();
}
#region IMovieRepository Members
public IList<Movie> ListAll()
{
var movies = from m in _dataContext.Movies
select m;
return movies.ToList();
}
#endregion
}

and a controller that uses this repository pattern to return a list of movies from the database:

namespace MvcApplication1.Controllers
{
public class MoviesController : Controller
{
private IMovieRepository _repository;
public MoviesController() : this(new MovieRepository())
{
}
public MoviesController(IMovieRepository repository)
{
_repository = repository;
}
public ActionResult Index()
{
return View(_repository.ListAll());
}
}
}

My question is, what code do i need to place in my view in order to display this data? AND what options do i have for displaying data in an ASP.Net MVC View?

Help greatly appreciated.

Upvotes: 1

Views: 800

Answers (2)

David
David

Reputation: 15360

Whilst using the IDE to create your Views is a fast way for development I think you need to understand how the ViewModel works.

Create your View page and at the top of your page declaration that tells the ViewPage what object to expect. Now you have strongly typed your View to understand what it should display

<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master"
Inherits="System.Web.Mvc.ViewPage<MvcApplication1.Models.Movie>" %>

<% foreach (Movie m in ViewData.Model) { %>
   <%= m.PropertName %> and other html
<% } %>

Remember also to add the namespace of your Models to your web.config. This enables you to write short Movie instead of MvcApplication1.Models.Movie.

<pages>
    <namespaces>
        <add namespace="MvcApplication1.Models" />

Upvotes: 1

Ben Scheirman
Ben Scheirman

Reputation: 40961

Right click on your controller, Add View...

  • Keep the name of the view the same as the action.
  • Check [X] create strongly typed view
    • Put IEnumerable<Movie> in the Type box

Your view will be created, and you can access the items by doing this:

<% foreach(var movie in Model) { %>

....

<% } %>

Upvotes: 3

Related Questions