简体   繁体   English

在MVC剃刀代码后面循环遍历模型

[英]loop through model in mvc razor code behind

I am working on MVC4 App, and I am stuck at one point, I tried using google to help me, but without success. 我正在开发MVC4 App,但我一度陷入困境,我尝试使用Google来帮助我,但未成功。 This might be more simple then I think, but coming from web forms and shifting to mvc is "painful" sometime. 我认为这可能更简单,但是从Web表单转移到mvc有时是“痛苦的”。 I am trying to loop through the model I have and get the values stored in that model. 我试图遍历我拥有的模型并获取存储在该模型中的值。 I tried few approaches but I am getting an error everytime. 我尝试了几种方法,但每次都会出错。 This is what I have: 这就是我所拥有的:

var modelAgentFilter = from s in _aa.Agents
                       where s.COUNTER == Convert.ToInt32(AgentID)
                       select s;
if (modelAgentFilter != null)
{                                         
    ViewBag.FirstName = // Get FirstName object here
}

Thanks in advance for your comments. 预先感谢您的评论。 Laziale Laziale

EDIT: 编辑:

I did include for loop like this: 我确实包括了这样的for循环:

   if (modelAgentFilter != null)
                {
                    foreach (var property in modelAgentFilter)
                    {
                        string test = property.ADDRESS;
                    }           
                }

But when the compiler will reach the foreach step I am getting this error: "LINQ to Entities does not recognize the method 'Int32 ToInt32(System.Object)' method, and this method cannot be translated into a store expression." 但是当编译器到达foreach步骤时,我收到此错误:“ LINQ to Entities无法识别方法'Int32 ToInt32(System.Object)',并且该方法无法转换为存储表达式。”

I can get to the properties of the var model using that foreach look but as soon as the compiler will try to loop the model that error pops up. 我可以使用foreach外观来获取var模型的属性,但是一旦编译器尝试循环出现该错误的模型,便可以使用。 Thanks again 再次感谢

LINQ to Entities does not recognize any methods. LINQ to Entities无法识别任何方法。 You can't use even ToString() in LINQ expression. 您甚至不能在LINQ表达式中使用ToString()。 You need first convert your value and than add it in LINQ. 您首先需要转换您的值,然后再将其添加到LINQ中。

In your example you need to do something like following: 在您的示例中,您需要执行以下操作:

var _agentID = int.Parse(AgentID);

var modelAgentFilter = from s in _aa.Agents
                       where s.COUNTER == _agentID 
                       select s;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM