具有匿名类型模型类的剃刀视图。有可能的?

问题描述 投票:19回答:4

我想使用razor模板创建一个视图,但我不想为模型编写一个类,因为在许多视图中我将有许多查询将返回不同的模型。

例如,我有一个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 */
};

我需要为此查询编写一个View。此查询返回文章。

现在我不知道应该如何看起来像模型定义。

我试着用这个定义:

@model System.Collections.IEnumerable

但后来我遇到一个错误,该文件在对象类型中不存在:

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

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

c# asp.net-mvc asp.net-mvc-3 razor anonymous-types
4个回答
42
投票

简短的回答是using anonymous types is not supported,然而,there is a workaround,你可以使用ExpandoObject

将您的模型设置为@model IEnumerable<dynamic>

然后在控制器中

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

1
投票

我认为这是一个更好的解决方案:

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

这允许嵌套的匿名类型,前面提到的扩展对象解决方案将无法处理。


1
投票

看起来你不能传递匿名类型,但如果你只想要类型的值,你可以传递一个可枚举的对象数组来查看。

视图:

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

控制器:

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


        }

    }

1
投票

如果您使用C#7.0+(在Visual Studio 2017+中引入),最简单的解决方案是使用元组而不是匿名类型。

剃刀视图:“_ MyTupledView.cshtml”

@model (int Id, string Message)

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

然后当你绑定这个视图时,你只需发送一个元组:

var id = 123;
var message = "Tuples are great!";
return View("_MyTupledView", (id, message))
© www.soinside.com 2019 - 2024. All rights reserved.