在ViewBag馅匿名类型引起模型绑定问题 [英] Stuffing an anonymous type in ViewBag causing model binder issues

查看:625
本文介绍了在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 ,我得到的结果 {=东西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馅匿名类型引起模型绑定问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆