Scott Selby
Scott Selby

Reputation: 9570

Displaying results in View linq to sql mvc 4

I have been reading and reading , and I can't seem to get this to work at all. I am very very new to asp.net MVC - after all the tutorials I read I finally got this much accomplished.

public class EventsController : Controller
{
    private EventsDBDataContext db = new EventsDBDataContext();
    public ActionResult Index()
    {
        var a = (from x in db.tblEvents
                 where x.StartDate >= DateTime.Now
                 select x).Take(20).ToList();
        return View(a);
    }
}

This is successfully finding 20 rows (like it is supposed to). Now how do I display these in the view ?? Does it have to be a strongly typed view?? It doesn't seem like it should have to be... I have tried both , I tried typing a whole view, but for now it would be nice to just get one property of tblEvents to show up in the view. This is not working, I have tried many many variations.

@{foreach( var item in Model){

      @Html.DisplayFor( item.ID)

  }
}

How do I get the results from the controller displayed in the view? Just the ID is good for now - I can go from there.

Upvotes: 1

Views: 5488

Answers (3)

Dirk Boer
Dirk Boer

Reputation: 9065

The problem is that your View doesn't know what type your Model is. Use the @model syntax to define the type of your model.

@model List<YourEventClass>

@foreach( var item in Model )
{
   @item.ID<br />
}

See i.e. here for more information

Upvotes: 1

Scott Selby
Scott Selby

Reputation: 9570

I guess you can not do something like this:

@{foreach( var item in Model){
   @Html.DisplayFor(modelItem => item.ID)
 }

unless the view knows what Type Model is returned as (still seems weird that .Net can't figure that out on its own. So I fixed the problem and got the ID displayed properly by adding this to the View.

@model IEnumerable<GetEvents.Models.tblEvent>

This works fine for this example - I am returning one table , so the Model type is just the class for the table. But this doesn't seem right - what if I wanted to query and join tables then what would the Model Type be?? Adding this fixed my problem , but if someone has a better answer for this then I will accept that.

Upvotes: 0

Jason Meckley
Jason Meckley

Reputation: 7591

from the root of the web project you should have a directory called Views. Within the views folder create a new folder named Events. In the Events folder create a razor view named Index. put your markup and template code in this file.

You are correct, views do not need to be strongly typed. I find it's a good idea to do so because it provides another compile time check, but it's not required.

when you run the application you will navigate from the root (typically home/index) to Events/Index. there you should see the list of 20 items rendered in the view.

Upvotes: 0

Related Questions