【问题标题】:MVC3: Access a property of an Object in the viewMVC3:在视图中访问对象的属性
【发布时间】:2012-06-06 18:51:10
【问题描述】:

在 ASP.NET MVC3 Web 应用程序中。

我有意见。视图有一个 IEnumerable 模型。

我需要遍历模型的所有项目并显示 item.Name

观点:

@model IEnumerable<Object> 
@{
    ViewBag.Title = "Home";
}

@foreach (var item in Model)
{ 
    <div class="itemName">@item.Name</div>
}

在控制器中,我使用 Linq to entity 从数据库中获取对象列表。

控制者:

public ActionResult Index()
{
    IEnumerable<Object> AllPersons = GetAllPersons();
    return View(AllSurveys);
}

public IEnumerable<Object> GetAllPersons()
{
    var Context = new DataModel.PrototypeDBEntities();
    var query = from p in Context.Persons
                select new
                {
                    id = p.PersonsId,
                    Name = p.Name,
                    CreatedDate = p.CreatedDate
                };
    return query.ToList();
}

运行时出现此错误:

 'object' does not contain a definition for 'Name' and no extension method 'Name' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?)

如何访问模型项的“名称”属性?

非常感谢您的帮助

【问题讨论】:

    标签: c# asp.net-mvc-3 razor


    【解决方案1】:

    为您的方法返回创建一个强类型。

    public class MyObject {
        public int id {get;set;}
        public string Name {get;set;}
        public DateTime CreatedDate {get;set;}
    }
    
    public IQueryable<MyObject> GetAllPersons() 
    { 
        var Context = new DataModel.PrototypeDBEntities(); 
        var query = from p in Context.Persons 
                    select new MyObject
                    { 
                        id = p.PersonsId, 
                        Name = p.Name, 
                        CreatedDate = p.CreatedDate 
                    }; 
        return query;
    } 
    

    ...然后更新您的视图以反映新模型...

    @model IQueryable<MyObject> 
    

    【讨论】:

      【解决方案2】:

      最简单的方法是定义一个类Person,并将您的模型/控制器更改为使用IEnumerable&lt;Person&gt; 而不是对象。

      【讨论】:

        【解决方案3】:

        你可能需要明确的Casting

        @(string) item.Name
        

        或使用dynamic 类型。

        在视图中,改变

        @model IEnumerable<Object> 
        

        @model IEnumerable<dynamic> 
        

        【讨论】:

          【解决方案4】:

          您的模型类型为IEnumerable&lt;Object&gt;,将其更改为IEnumerable&lt;Person&gt;,以便您可以访问Person 属性。

          【讨论】:

            【解决方案5】:

            我可能错了,但您可以尝试使用 IEnumerable&lt;dynamic&gt; 而不是 IEnumerable&lt;Object&gt;

            【讨论】:

              猜你喜欢
              • 2019-08-14
              • 1970-01-01
              • 2010-11-11
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多