本文介绍了在 ViewBag 中填充匿名类型导致模型绑定问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

谁能告诉我我做错了什么?:-)

can someone tell me what I'm doing wrong? :-)

我有一个简单的查询:

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

然后我将它传递给 ViewBag.

And I pass this to ViewBag.

ViewBag.Sample = sample;

然后我想像这样在我的视图中访问它:

Then I want to access it in my view like this:

@foreach (var item in ViewBag.Sample) {
    @item.Something
}

我收到错误消息对象"不包含某物"的定义.如果我只把 @item 放在那里,我会得到结果 {Something = SomeUserName }

And I get error message 'object' does not contain a definition for 'Something'. If I put there just @item, I get result { Something = SomeUserName }

感谢您的帮助.

推荐答案

这是不可能的.ViewBag 是动态的,问题是匿名类型是作为内部生成的.我建议您使用视图模型:

This cannot be done. ViewBag is dynamic and the problem is that the anonymous type is generated as internal. I would recommend you using a view model:

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

并在视图中:

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

这篇关于在 ViewBag 中填充匿名类型导致模型绑定问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 06:25