获取的Razor视图来了解LINQ到SQL对象 [英] Getting Razor View to understand Linq to SQL objects

查看:135
本文介绍了获取的Razor视图来了解LINQ到SQL对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过一个循环的结果,从一个LINQ调用SQL函数返回的对象列表的视图。但是,我不知道怎么去处理L2S对象(为了使用foreach)的看法。

在控制器:

 计算机[名单] = db.Users.ToList();


解决方案

控制器:

 公共类MyClassController:控制器
{
    私人ProjectContext DB =新ProjectContext();    //
    // GET:/ MyClass的/    公众的ViewResult指数()
    {
        返回查看(db.MyClasses.ToList());
    }
}

查看:

  @model IEnumerable的< MvcApplication1.Models.MyClass>
@foreach(以型号VAR项){
    < D​​IV>
    <! - HTML喜欢这里@ item.Title - >
    < / DIV>
}

这是强类型化视图的方法。采用动态方法是没有太大的不同。刚分配您的列表中动态对象的属性,然后,而不是的foreach(在型号VAR项目)变成的foreach(在ViewBag VAR项目。的ListProperty)。或ViewData的分配 ViewData.Add中的ViewData(名单',db.MyClasses.ToList())并在foreach成为的foreach(VAR项目['名单']) I preFER强类型的方法,因为它看起来十分干净多了。

编辑:在评论中提出了(我忘了,因为我几乎完全使用强类型的方法)良好的一点是,你必须赶出去。在这种情况下,它存储为列表< MyClass的> 虽然你也可以含蓄地拉出来作为一个的IEnumerable< MyClass的>

I would like to loop through a result in a view from a call to a LINQ to SQL function that returns a list of objects. However, I am not sure how to get the view to handle the L2S object (in order to use a foreach).

In the controller:

  ViewData["list"] = db.Users.ToList();

解决方案

Controller:

public class MyClassController : Controller
{
    private ProjectContext db = new ProjectContext();

    //
    // GET: /MyClass/

    public ViewResult Index()
    {
        return View(db.MyClasses.ToList());
    }
}

View:

@model IEnumerable<MvcApplication1.Models.MyClass>


@foreach (var item in Model) {
    <div>
    <!-- HTML here like @item.Title -->
    </div>
}

This is the strongly typed view methodology. Using the dynamic approach it isn't much different. Just assigning your list to a property on the dynamic object and then instead of foreach(var item in Model) it becomes foreach(var item in ViewBag.listProperty). Or with ViewData you assign ViewData.Add('list', db.MyClasses.ToList()) and the foreach becomes foreach(var item in ViewData['list']) I prefer the strongly typed approach as it seems much much cleaner.

EDIT: good point brought up in comments (that I forgot since I almost exclusively use the strongly typed approach) is that you'll have to cast out. In this case it is stored as a List<MyClass> though you can also implicitly pull it out as an IEnumerable<MyClass>

这篇关于获取的Razor视图来了解LINQ到SQL对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆