views:

406

answers:

2

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.

+3  A: 

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) { %>

....

<% } %>
Ben Scheirman
right clicking on the controller unfortunately doesnt give me the option to add a view?
Goober
If you're using the release of the MVC framework, you should have the IDE tooling to Add a View directly from the controller. If not, you might want to re-run the installer.In any case, you can follow my instructions but build the view manually.
Ben Scheirman
+1  A: 

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" />

David Liddle