gpt4 book ai didi

asp.net-mvc - Asp.Net MVC 4 模型

转载 作者:行者123 更新时间:2023-12-02 01:52:07 25 4
gpt4 key购买 nike

你好 friend ,我在 mvc 4 中遇到问题,无法在 View 中发送动态模型建议我如何将动态模型与 View 绑定(bind)

这是我的 Action

[ChildActionOnly]

public ActionResult TopArticles()
{
var model = from a in db.Articles.Take(3).OrderBy(m=>m.TotalViews)
join u in db.UserProfiles
on a.CreatedBy equals u.ID
join t in db.Tags
on a.TagID equals t.ID
select new
{
Title = a.Title,
ArticleID = a.ArticleID,
FirstName = u.FirstName,
CreatedBy = a.CreatedBy,
TagID = a.TagID,
TagName = t.Name,
CreationDate = a.CreationDate,
TotalViews = a.TotalViews
}; // get Top 3 Articles from Articles
return PartialView(model);
}

这是我的观点

 @model IEnumerable<dynamic>
@{
ViewBag.Title = "TopArticles";
}
@foreach(dynamic item in Model)
{
<div class="row about_topviewedarticle1">
<div class="row">
<div class="columns twenty">
<a href="#" class="title">@item.Title</a>
by <a href="#"class="profilefont_eleven">@item.FirstName</a>
</div>
</div>
<div class="row">
<div class="columns twenty">
<label class="font_ten">views: @item.TotalViews posted on : @item.CreationDate</label>
</div>
</div>
</div>
}

当我运行这段代码时,出现以下错误

'object' does not contain a definition for 'Title'

最佳答案

第一种方式

试试这个

var model = from a in db.Articles.Take(3).OrderBy(m=>m.TotalViews) 
join u in db.UserProfiles
on a.CreatedBy equals u.ID
join t in db.Tags
on a.TagID equals t.ID
**select new Article**
{
Title = a.Title,
ArticleID = a.ArticleID,
FirstName = u.FirstName,
CreatedBy = a.CreatedBy,
TagID = a.TagID,
TagName = t.Name,
CreationDate = a.CreationDate,
TotalViews = a.TotalViews
};

According to David Ebbo, you can't pass an anonymous type into a dynamically-typed view because the anonymous types are compiled as internal. Since the CSHTML view is compiled into a separate assembly, it can't access the anonymous type's properties.

See this discussion

或者,

第二种方式

立即将匿名对象转换为 ExpandoObject。

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



var model = from a in db.Articles.Take(3).OrderBy(m=>m.TotalViews)
join u in db.UserProfiles
on a.CreatedBy equals u.ID
join t in db.Tags
on a.TagID equals t.ID
select new
{
Title = a.Title,
ArticleID = a.ArticleID,
FirstName = u.FirstName,
CreatedBy = a.CreatedBy,
TagID = a.TagID,
TagName = t.Name,
CreationDate = a.CreationDate,
TotalViews = a.TotalViews
}**.ToExpando()**;

引用自 herehere

关于asp.net-mvc - Asp.Net MVC 4 模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22168012/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com