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

How to pass result of a lambda expression to view

我正在使用 asp.net mvc 5。在我的模型中,我有两个 table 称为 "User"、"User preferences".

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

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

我需要,当电子邮件作为参数传递给操作方法时,通过使用该电子邮件 select 该用户的 ID 并使用条件 ID=UserID 加入两个 tables 并传递结果 view.In 我想显示该用户的 CategoryID 的视图。 我试过的代码是 ;

动作结果;

 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.DbQuery1[<>f__AnonymousType11[System.Nullable1[System.Int32]]]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable1[MvcApp.Models.UserPreference]'类型。

我的代码有什么问题??

只需将 x1 传递给 ViewBag

 ViewBag.ABC = x1

在视图中访问此内容

var x1 = ViewBag.ABC;

这里的问题是您正在创建 AnonymousType 并将其传递给视图,但是在视图中您将模型声明为不同的类型,因此异常是 thrown.So 您必须使用在视图中声明的与模型相同的类型。所以您需要像下面这样更改您的连接查询。

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);

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

类型的对象

尝试以下操作,问题是因为您return输入的类型与您预期的类型不同

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);

如果 table 不包含 MvcApp.Models.UserPreference,您将需要更改 select 语句以创建适当类型的对象。

即将 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(即您正在 returning up

然后添加以下内容。

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

ToArray() 调用将强制停止数据库查询和 return 对象数组,这样您就不会得到异常。