如何在ASP.Net中的视图中循环返回结果 [英] How do I loop through returned results in a view in ASP.Net

查看:48
本文介绍了如何在ASP.Net中的视图中循环返回结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

HI全部,

在我的项目中...

我有一个这样的动作结果:





HI All,
In my project...
I have got an Action Result like this:


public ActionResult GetPartNumber(string Id)
  {
        private readonly PartNumberEntities _Context = new PartNumberEntities();
      var partnumber = _Context.Parts.SingleOrDefault(x => x.ITEMID == Id);
      ViewData["Id"] = Id;



      return PartialView("_PartNumbers", partnumber);

  }





在我看来,我有这个:



In my view I have this:

@{
   
  

    string partumber = ViewData["id"] as string;
}


            @foreach (var item in Model)
            {
               
            }





我想遍历所有返回的结果但是正如你在我看来所看到的,我正在使用foreach循环但由于某种原因它不会让访问属性。例如,如果我想查看foreach循环中的partnumbers列,如下所示:





I want to loop through all the returned results but as you can see in my view , i am using foreach loop but for some reason it won't let access the properties. for example if i want to look through partnumbers column inside the foreach loop like so:

@foreach(var item in Model){

item.partnumber // here it doesn't even like auto suggest or dropdown option for partnumber.. am i missing anything?? please help?


}

推荐答案

你需要告诉视图你的模型是什么类型的@model指令



@model部分



使用你需要的任何类型,我猜它被称为Part,因为你在控制器中使用var是不可能的。您可能还需要完整的命名空间



@model MyNamespace.Part



除非部分也是一个IEnumerable,你将无法使用foreach。



访问模型是MVC的一个基本方面,我建议你去通过一本书或一些在线教程来了解基础知识。
You need to tell the view what type your Model is via the @model directive

@model Part

use whatever type you need, I've just guessed it is called Part, as you're using "var" in the controller it's impossible to say. You might need the full namespace as well

@model MyNamespace.Part

Also unless "Part" is also an IEnumerable you won't be able to use a foreach on it.

Accessing the model is quite a basic aspect of MVC, I'd recommend you go through a book or some online tutorials to get an understanding of the basics.


你可以从 ModelMetadata 获得。请参阅 - 循环查看视图中的模型属性 [ ^ ]。

You can get from ModelMetadata. Refer - Looping through view Model properties in a View[^].
@foreach(var property in ViewData.ModelMetadata.Properties)
{
    <div class="editor-line">
        <label>@(property.DisplayName??property.PropertyName)</label>
        @Html.Editor(property.PropertyName)
    </div>
}


这篇关于如何在ASP.Net中的视图中循环返回结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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