gpt4 book ai didi

entity-framework - 在 ViewBag 中填充匿名类型会导致模型绑定(bind)器问题

转载 作者:行者123 更新时间:2023-12-04 05:26:37 27 4
gpt4 key购买 nike

有人可以告诉我我做错了什么吗? :-)

我有这个简单的查询:

 var sample = from training in _db.Trainings
where training.InstructorID == 10
select new { Something = training.Instructor.UserName };

我将它传递给 ViewBag。
ViewBag.Sample = sample;

然后我想像这样在我的 View 中访问它:
@foreach (var item in ViewBag.Sample) {
@item.Something
}

我收到错误消息“对象”不包含“某物”的定义。如果我把 @item 放在那里, 我得到结果 { Something = SomeUserName }
感谢帮助。

最佳答案

这是无法做到的。 ViewBag 是动态的,问题是匿名类型是作为内部生成的。我建议您使用 View 模型:

public class Instructor
{
public string Name { get; set; }
}

进而:
public ActionResult Index()
{
var mdoel = from training in _db.Trainings
where training.InstructorID == 10
select new Instructor {
Name = training.Instructor.UserName
};
return View(model);
}

在 View 中:
@model IEnumerable<Instructor>
@foreach (var item in ViewBag.Sample) {
@item.Something
}

关于entity-framework - 在 ViewBag 中填充匿名类型会导致模型绑定(bind)器问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5649536/

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