如何将lambda表达式的结果传递给view

时间:2015-03-25 10:06:26

标签: c# asp.net-mvc lambda

我正在使用asp.net mvc 5.在我的模型中,我有两个名为“User”,“User preferences”的表。

在用户表中我有; ID 电子邮件 密码

在用户首选项表中我有 用户身份 类别ID

我需要,当电子邮件作为参数传递给action方法时,通过使用该电子邮件选择该用户的ID&使用条件ID =用户ID&加入两个表将结果传递给view。在视图中,我想显示该用户的CategoryID。 我试过的代码是;

的ActionResult;

 public class LoggedInController : Controller

{

    private EPlannerDatabaseEntities db = new EPlannerDatabaseEntities();
    //
    // GET: /LoggedIn/
    public ActionResult Index(String email)
    {
        var Items = from m in db.Users
                    select m;
        if (!String.IsNullOrEmpty(email))
        {
            Items = Items.Where(s => s.Email.Contains(email));

        }

        var x1 = Items.Join(db.UserPreferences, vp => vp.Id, up => up.UserId, (vp, up) => new { Id = up.UserId });
        return View(x1);


    }
}

}

我的观点是;

@model IEnumerable<MvcApp.Models.UserPreference>

@{
ViewBag.Title = "Index";
}

<h2>Blah</h2>

@foreach (var x1 in Model)
{

<h1>@x1.CategoryId</h1>


}

但是当我运行该程序时,它显示以下错误:

传递到字典中的模型项的类型为'System.Data.Entity.Infrastructure.DbQuery 1[<>f__AnonymousType1 1 [System.Nullable 1[System.Int32]]]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable 1 [MvcApp.Models.UserPreference]'。

我的代码有什么问题?

3 个答案:

答案 0 :(得分:1)

这里的问题是你正在创建AnonymousType并将其传递给视图,但是在视图中你将模型声明为不同的类型以便抛出异常。因此你必须使用视图中声明的相同类型作为模型。所以你需要更改你的连接查询,如下所示。

var x1 = Items.Join(db.UserPreferences, vp => vp.Id, up => up.UserId, (vp, up) => new MvcApp.Models.UserPreference{ UserId = up.UserId }).ToList();
return View(x1);

答案 1 :(得分:1)

我假设db.UserPreferences包含MvcApp.Models.UserPreference

类型的对象

尝试以下方法,问题是您没有返回与预期视图相同的类型

private EPlannerDatabaseEntities db = new EPlannerDatabaseEntities();
//
// GET: /LoggedIn/
public ActionResult Index(String email)
{
  var x1 = from m in db.Users
          where String.IsNullOrEmpty(email) || m.Email.Contains(email)
          join up in db.UserPreferences 
          on m.Id equals up.UserId
          select up;
  return View(x1);
}

或者,如果您想维护现有代码,只需将连接线更改为

即可
 var x1 = Items.Join(db.UserPreferences, vp => vp.Id, up => up.UserId, (vp, up) => up);

如果表格不包含MvcApp.Models.UserPreference,则需要更改select语句以创建approriate类型的对象。

即将select up行更改为

select new MvcApp.Models.UserPreference { 
      UserId = up.UserId,
      Category = ....
}

或者,如果您使用备用Join语句,则需要将(vp,up) => up更改为

(vp,up) => new MvcApp.Models.UserPreference { 
      UserId = up.UserId,
      Category = ....
}

编辑更新

看到您对Manish Parakhiya的评论,您可能需要首先从数据库查询转换为使用Mvc对象。

如果是这种情况,请使用我的前两个解决方案之一来生成x1(即您正在返回up

然后添加以下内容。

var x2 = x1.ToArray().Select(up => new MvcApp.Models.UserPreference { UserId= up.UserId, Cat......});
return View(x2);

ToArray()调用将强制数据库查询消失并返回对象数组,然后您将无法获得异常。

答案 2 :(得分:-2)

将x1传递给ViewBag

 ViewBag.ABC = x1

在视图

上访问它
var x1 = ViewBag.ABC;