本文介绍了剃刀视图具有匿名类型的模型类。有可能的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我想用剃刀模板创建一个视图,但我不想写模型类,因为在很多的意见我都会有这将返回diferent模型许多查询。

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.

例如我有一个LINQ查询:

For example I have a linq query:

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.

我试图用这个deffinition:

I tried to use this deffinition:

@model System.Collections.IEnumerable

但后来我有一个误差修改比犯规存在于对象类型个行业:

But then I had an erros than fileds doesnt exists in object type:

* CS1061:'对象'不包含'addition_field',没有扩展方法'addition_field接受型对象的第一个参数可以找到一个定义*

*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*

这是我的模型,我不想写一个模型。当然

This is my model for which I do not want to write a next model. Of course

推荐答案

简短的回答是,using匿名类型不支持,但是,there是一种解决方案,则可以使用 ExpandoObject

The short answer is that using anonymous types is not supported, however, there is a workaround, you can use an ExpandoObject

设置你的模型
@model IEnumerable的<动态>

然后在控制器

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

这篇关于剃刀视图具有匿名类型的模型类。有可能的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 22:10