user1821732
user1821732

Reputation: 95

mvc3 How can I read on razor a list created by joining two tables?

I have this mvc3 project, I am learning actually and here I am joining 2 tables from the same database, but I don't know how I can return it to the View, and on the View I don't know how to read it.

public ActionResult Index()
    {
        ViewBag.Message = "List of Domain Names already crawlered";
        domainNamesEntities de = new domainNamesEntities();

        var datos = from nombres in de.tableDomNames
                    join titulos in de.tableTitleNames on nombres.domName equals titulos.domName
                    select new { Dominio = nombres.domName, Titulo = titulos.titleN };

        return View(datos.ToList());
    }

And here is my problem:

       @model ???????????????
       @{
             ViewBag.Title = "Index";
        }

        <h2>Index</h2>

      @foreach (var item in collection???????)
{

}

Any ideas?

thanks!

Upvotes: 4

Views: 507

Answers (1)

Eric J.
Eric J.

Reputation: 150148

The variable datos has an anonymous type. While you can pass that into a view, you cannot specify a strong type for Model in the view.

If you need a strong type, create a helper object containing your properties, e.g.

public class MyHelper
{
    public string Dominio { get; set; }
    public string Titulo { get; set; }
}

and use

select new MyHelper { Dominio = nombres.domName, Titulo = titulos.titleN };

In the view, you would then specify

@model IEnumerable<MyHelper> 

@foreach (var item in Model) // or MyHelper item in Model

Upvotes: 4

Related Questions