简体   繁体   English

razor 视图与匿名类型 model class。 有可能的?

[英]razor view with anonymous type model class. It is possible?

I want to create a view using razor template, but I do not want to write a class for model, because in many views i will have many queries which will be returning diferent models.我想使用 razor 模板创建一个视图,但我不想为 model 编写一个 class,因为在许多视图中我会有很多查询将返回不同的模型。

For example I have a linq query:例如我有一个 linq 查询:

from p in db.Articles.Where(p => p.user_id == 2)
select new
{
    p.article_id, 
    p.title, 
    p.date, 
    p.category,
    /* Additional parameters which arent in Article model */
};

I need to write a View for this query.我需要为此查询编写一个视图。 This query returns a Articles.此查询返回文章。

Now I dont know how should looks like a model definition.现在我不知道应该如何看起来像 model 定义。

I tried to use this deffinition:我试图使用这个定义:

@model System.Collections.IEnumerable

But then I had an erros than fileds doesnt exists in object type:但是后来我有一个错误,而不是 object 类型中不存在的文件:

*CS1061: 'object' does not contain a definition for 'addition_field' and no extension method 'addition_field' accepting a first argument of type 'object' could be found* *CS1061:“object”不包含“addition_field”的定义,并且找不到接受“object”类型的第一个参数的扩展方法“addition_field”*

This is my model for which I do not want to write a next model.这是我的 model,我不想为此写下一个 model。 Of course当然

The short answer is that using anonymous types is not supported , however, there is a workaround , you can use an ExpandoObject简短的回答是不支持使用匿名类型,但是, 有一种解决方法,您可以使用ExpandoObject

Set your model to @model IEnumerable<dynamic>将您的 model 设置为@model IEnumerable<dynamic>

Then in the controller然后在 controller

from p in db.Articles.Where(p => p.user_id == 2)
select new
{
    p.article_id, 
    p.title, 
    p.date, 
    p.category,
    /* Additional parameters which arent in Article model */
}.ToExpando();

...
public static class Extensions
{
    public static ExpandoObject ToExpando(this object anonymousObject)
    {
        IDictionary<string, object> anonymousDictionary = HtmlHelper.AnonymousObjectToHtmlAttributes(anonymousObject);
        IDictionary<string, object> expando = new ExpandoObject();
        foreach (var item in anonymousDictionary)
            expando.Add(item);
        return (ExpandoObject)expando;
    }
}

It seems you can't pass anonymous types but if you just want the values of the type you might pass an enumerable of an object array to view.似乎您不能传递匿名类型,但如果您只想要该类型的值,您可以传递一个 object 数组的可枚举来查看。

View:看法:

@model IEnumerable<object[]>   

@{
    ViewBag.Title = "Home Page";
}

<div>   
    <table>
        @foreach (var item in Model)
        {
            <tr>
                <td>@item[0].ToString()</td>
                <td>@item[1].ToString()</td>
            </tr>
        }
    </table>
</div>

Controller: Controller:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;

    namespace ZZZZZ
    {
        public class HomeController : Controller
        {
            public ActionResult Index()
            {

                List<object[]> list = new List<object[]> { new object[] { "test1", DateTime.Now, -12.3 } };

                return View(list);
            }


        }

    }

The simplest solution if you are using C# 7.0+ (introduced in Visual Studio 2017+) is to use a tuple rather than an anonymous type.如果您使用 C# 7.0+(在 Visual Studio 2017+ 中引入),最简单的解决方案是使用元组而不是匿名类型。

Razor View: "_MyTupledView.cshtml" Razor 查看:“_MyTupledView.cshtml”

@model (int Id, string Message)

<p>Id: @Model.Id</p>
<p>Id: @Model.Message</p>

Then when you bind this view, you just send a tuple:然后,当您绑定此视图时,您只需发送一个元组:

var id = 123;
var message = "Tuples are great!";
return View("_MyTupledView", (id, message))

I think this is an even better solution:我认为这是一个更好的解决方案:

http://buildstarted.com/2010/11/09/razor-without-mvc-part-iii-support-for-nested-anonymous-types/ http://buildstarted.com/2010/11/09/razor-without-mvc-part-iii-support-for-nested-anonymous-types/

This allows for nested anonymous types, which the aforementioned expando-object solution won't handle.这允许嵌套匿名类型,上述扩展对象解决方案无法处理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM