ASP/MVC3 Razor Linq[英] ASP/MVC3 Razor Linq

本文是小编为大家收集整理的关于ASP/MVC3 Razor Linq的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

我一直为我的项目遇到这个错误.

传递到字典的模型项是类型 'system.collections.generic.list 1[<>f__AnonymousType2 2 [System.String,System.String]]', 但是该词典需要类型的模型项 'system.collections.generic.ienumosith`1 [etms.models.db.tblparent]'.

描述:执行期间发生了一个未经治疗的例外 当前的Web请求.请查看堆栈跟踪以获取更多 有关错误及其起源于代码的信息.

=================================================== ===============================

我想做的是从数据库中检索数据(一到多个),这是我的数据库表结构

tblparent
- Parent_ID
- Username
- Password
- Firstname
- Lastname

tblParentEmail
- ParentEmail_ID
- Email
- Parent_ID

我是从电子邮件到父母的外国关系,但是在还有另一个错误时,我无法将EF包含在EF中.我这样做了,并导致了我这个错误:

public ActionResult Clientlist()
{
    using (ETMSPeopleEntities db = new ETMSPeopleEntities())
    {
        //var sxc = db.tblParents.Include("tblLocation").Include("tblParentEmails.ParentEmail_ID")
        //    .OrderByDescending(p => p.Status).ToList();
        var members = (from x in db.tblParentEmails
                      join y in db.tblParents
                      on x.Parent_ID equals y.Parent_ID 
                      select new { Email = x.ParentEmail, UserName = y.Username }).AsEnumerable();
        return View(members.ToList());
    }
}

这是我的admincontroller

@model IEnumerable<ETMS.Models.DB.tblParent>
@{
    ViewBag.Title = "Clientlist";
}

<h2>Clientlist</h2>

<p>
    @Html.ActionLink("Create New", "Create")
</p>
<table>
    <tr>
        <th>
            Username
        </th> 
        <th></th>
    </tr>

@foreach (var item in Model) {
    <tr> 
        <td>
            @Html.DisplayFor(modelItem => item.Username)
        </td>
         <td>
            @Html.DisplayFor(modelItem => item.Firstname)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Lastname)
        </td>
          <td>
            @Html.DisplayFor(modelItem => item.Location_ID)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Email)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.CreateTime)
        </td>
        <td>
            @Html.ActionLink("Edit", "Edit", new { id=item.Parent_ID }) |
            @Html.ActionLink("Details", "Details", new { id=item.Parent_ID }) |
            @Html.ActionLink("Delete", "Delete", new { id=item.Parent_ID })
        </td>
    </tr>
}

</table>

这是客户列表视图

推荐答案

您正在将匿名对象的列表传递给您的视图:

select new { Email = x.ParentEmail, UserName = y.Username }

当视图期望IEnumerable<ETMS.Models.DB.tblParent>:

@model IEnumerable<ETMS.Models.DB.tblParent>

您应该将选择更改为:

select y

为了使代码工作.

更新

这是您可以使用视图模型模式的方式.首先,创建一个视图模型类,因此您不会将匿名类型传递给视图.我们称其为AwesomeEmailViewModel,看起来您需要.Email,.Username和其他一些属性,所以我们也将其设置为.

public class AwesomeEmailViewModel
{
    public string Email { get; set; }
    public string Username { get; set; }
    public string FirstName{ get; set; }
    public string LastName { get; set; }
    public int Location_ID{ get; set; }
    public DateTime CreateTime { get; set; }
}

现在,通过使用对象初始化填充AwesomeEmailViewModel

的实例来修改查询

注意:我是猜测哪些属性属于哪些对象(tblparent或tblparentemails,因此您需要对这些

进行仔细检查
var members = (from x in db.tblParentEmails
               join y in db.tblParents
               on x.Parent_ID equals y.Parent_ID 
               select new AwesomeEmailViewModel()
               { 
                   Email = x.ParentEmail, 
                   UserName = y.Username,
                   FirstName = y.FirstName,
                   LastName = y.LastName,
                   Location_ID = x.Location_ID,
                   CreateTime = y.CreateTime, 
               }).ToList();
               // I don't know if you'll need the `AsEnumerable()` call

return View(members);

最后,您的观点必须知道要期望的是什么类型,因此让我们对其进行修改,以期待我们新创建的AwesomemailViewModel实例的列表.

@model IEnumerable<ETMS.Models.AwesomeEmailViewModel>

正如我在名称空间上所猜的那样,请密切注意.无论如何,这应该使您可以访问视图内部所需的属性.如果您需要更多,则需要修改我们创建的新视图模型类以及控制器操作中的查询.

其他推荐答案

您的观点期望tblparent,但您正在将其传递给连接表.

您需要创建一个ViewModel,在此处加入您的桌子,然后更改视图以期望ViewModel而不是TBLPARENT.

这是大量示例.这是一个: asp.net mvc ViewModel模式

我希望这会有所帮助

戴维

其他推荐答案

在视图文件中,您需要eTms.models.db.tblparent的类型模型,并且在控制器中,您可以通过 members.tolist(),更改任意一个以使其匹配.

您可以创建像这样的ViewModel

public Class Client 
{ 
   public string Email {get;set;}
   public string UserName   {get;set;}
}

并在控制器操作中返回此列表,而不是匿名类型,您将在视图中定义客户端类型.

本文地址:https://www.itbaoku.cn/post/1556974.html

问题描述

I keep getting this error for my project.

The model item passed into the dictionary is of type 'System.Collections.Generic.List1[<>f__AnonymousType22[System.String,System.String]]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable`1[ETMS.Models.DB.tblParent]'.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

==================================================================================

What i want to do is to retrieve the data from the database (one to many) , This is my database table structure

tblparent
- Parent_ID
- Username
- Password
- Firstname
- Lastname

and

tblParentEmail
- ParentEmail_ID
- Email
- Parent_ID

i was made the foreign relation from email to parent, but i could not include with EF while there is another error. i do in this way and caused me this error :

public ActionResult Clientlist()
{
    using (ETMSPeopleEntities db = new ETMSPeopleEntities())
    {
        //var sxc = db.tblParents.Include("tblLocation").Include("tblParentEmails.ParentEmail_ID")
        //    .OrderByDescending(p => p.Status).ToList();
        var members = (from x in db.tblParentEmails
                      join y in db.tblParents
                      on x.Parent_ID equals y.Parent_ID 
                      select new { Email = x.ParentEmail, UserName = y.Username }).AsEnumerable();
        return View(members.ToList());
    }
}

This is my admincontroller

@model IEnumerable<ETMS.Models.DB.tblParent>
@{
    ViewBag.Title = "Clientlist";
}

<h2>Clientlist</h2>

<p>
    @Html.ActionLink("Create New", "Create")
</p>
<table>
    <tr>
        <th>
            Username
        </th> 
        <th></th>
    </tr>

@foreach (var item in Model) {
    <tr> 
        <td>
            @Html.DisplayFor(modelItem => item.Username)
        </td>
         <td>
            @Html.DisplayFor(modelItem => item.Firstname)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Lastname)
        </td>
          <td>
            @Html.DisplayFor(modelItem => item.Location_ID)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Email)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.CreateTime)
        </td>
        <td>
            @Html.ActionLink("Edit", "Edit", new { id=item.Parent_ID }) |
            @Html.ActionLink("Details", "Details", new { id=item.Parent_ID }) |
            @Html.ActionLink("Delete", "Delete", new { id=item.Parent_ID })
        </td>
    </tr>
}

</table>

this is clientlist view

推荐答案

You're passing a list of anonymous objects to your view:

select new { Email = x.ParentEmail, UserName = y.Username }

While the view is expecting IEnumerable<ETMS.Models.DB.tblParent>:

@model IEnumerable<ETMS.Models.DB.tblParent>

You should change your selection to:

select y

in order for the code to work.

Update

Here is how you could use a view model pattern. First, create a view model class, so you're not passing an anonymous type to your view. Let's call it AwesomeEmailViewModel, and it looks like you need .Email, .Username and some other properties, so we'll set those up too.

public class AwesomeEmailViewModel
{
    public string Email { get; set; }
    public string Username { get; set; }
    public string FirstName{ get; set; }
    public string LastName { get; set; }
    public int Location_ID{ get; set; }
    public DateTime CreateTime { get; set; }
}

Now, modify your query by using object initialization to populate an instance of AwesomeEmailViewModel

Note: I am guessing which properties belong to which objects (either tblParent or tblParentEmails, so you will need to double-check these

var members = (from x in db.tblParentEmails
               join y in db.tblParents
               on x.Parent_ID equals y.Parent_ID 
               select new AwesomeEmailViewModel()
               { 
                   Email = x.ParentEmail, 
                   UserName = y.Username,
                   FirstName = y.FirstName,
                   LastName = y.LastName,
                   Location_ID = x.Location_ID,
                   CreateTime = y.CreateTime, 
               }).ToList();
               // I don't know if you'll need the `AsEnumerable()` call

return View(members);

Finally, your view has to know what type(s) to expect, so let's modify it to expect a list of our newly created AwesomeEmailViewModel instances.

@model IEnumerable<ETMS.Models.AwesomeEmailViewModel>

Pay close attention, as I guessed at the namespace as well. In any case, this should give you access to the properties you need inside your view. If you need more, you'll need to modify the new view model class we created as well as the query in your controller action.

其他推荐答案

Your view expects tblParent but you are passing it the joined table.

You need to create a ViewModel, join your tables there and change your view to expect the ViewModel rather than tblParent.

Thre are loads of examples. Here's one: ASP.NET MVC ViewModel Pattern

I hope this helps

Davy

其他推荐答案

In the view file, you require a model of type IEnumerable of ETMS.Models.DB.tblParent, and in the controller, you pass in members.ToList(), you have to change either one to make it match.

You can create a viewmodel like this

public Class Client 
{ 
   public string Email {get;set;}
   public string UserName   {get;set;}
}

And return a list of this instead of anonymous type in your controller action, and you will define IEnumerable of Client type in your view.