2011-07-07 67 views
18

我想創建一個使用剃刀模板的視圖,但我不想爲模型編寫一個類,因爲在很多視圖中,我將有許多查詢將返回不同的模型。具有匿名類型模型類的剃鬚刀視圖。有可能的?

比如我有一個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 */ 
}; 

我需要寫這個查詢視圖。這個查詢返回一個Articles。

現在我不知道應該如何看起來像一個模型定義。

我試圖用這個deffinition:

@model System.Collections.IEnumerable 

但後來我有一個錯誤回報比犯規存在於對象類型的Fileds:

* CS1061:「對象」不包含定義「addition_field '並且沒有擴展方法'addition_field'接受類型'object'的第一個參數可以被發現*

這是我不想寫下一個模型的模型。當然

+0

'@model System.Collections.IEnumerable

' –

+0

該查詢似乎投射'匿名類型的IEnumerable',而不是'Article' –

+0

你能解釋一下爲什麼你不想寫一個模型嗎?使用模型類有一些優點 - 例如您可以使用智能感知,您可以更多地使用部分類,並可以爲模型類添加驗證等屬性。 – Stuart

回答

39

簡短的回答是using anonymous types is not supported,但是,there is a workaround,你可以在控制器

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

非常感謝:) – nosbor

+0

+1我希望我能多勞多得。 'ToExpando'是一個好主意! –

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


     } 

    } 
+0

不錯:-) – netfed