将对象列表从控制器传递到 MVC4 中的视图

Passing list of objects from controller to View in MVC4

本文关键字:MVC4 视图 对象 列表 控制器      更新时间:2023-09-26

我是ASP/MVC的新手,作为其中的一部分,我开始使用一个简单的应用程序进行学习。

我在控制器中有一个对象集合,如下所示

    public ActionResult loadimage(String FQDN, String trange)
        {
            List<geo_crd> Geo_crd = new List<geo_crd>();
              //more logic

foreach (ToDoItem T in query1)
            {
                IEnumerable<GeoItem> query2 = (from b in db1.GeoItems
                                               where b.DNS_server_address == T.DNS_server_address
                                               select b);
                foreach (GeoItem X in query2)
                {
                    Geo_crd.Add(new geo_crd(X.DNS_latitude, X.DNS_longitude, 1));
                }
            }

            return View(Geo_crd);
        }

Geo_crd在模型中如下所示

namespace ToDoApp.Models
{
        public class geo_crd 
    {
        private Decimal _geo_lat;
        private Decimal _geo_long;
        private int _status_flag;
        public geo_crd(Decimal x, Decimal y, int z)
        {
            _geo_lat = x;
            _geo_long = y;
            _status_flag = z;
        }
        public Decimal geo_lat
        {
            get { return _geo_lat; }
            set { _geo_lat = value; }
        }
        public Decimal geo_long
        {
            get { return _geo_long; }
            set { _geo_long = value; }
        }
        public int status_flag
        {
            get { return _status_flag; }
            set { _status_flag = value; }
        }

    }
}

我收到的意见如下

@model IEnumerable <ToDoApp.Models.geo_crd>
// more code here 
<script type="text/javascript"> 
    @foreach (var item in Model){ 
            <spam><li> @item.geo_lat </li></spam>
            <span> <li> AddLocationPin(@item.geo_lat, @item.geo_long, null, 'place 1');</li> </span> 
           } 
  </script>

我遇到的问题是,服务器没有发送AddlocatioPin,我猜它只是忽略了它。

我真的在做傻事吗?请帮忙

你不应该用 script 来包装 html 标签。开始和结束标记,它们的顺序也必须在 html 中匹配。另外,您应该阅读有关HTML ul标签的更多信息

正确的观点是

@model IEnumerable <ToDoApp.Models.geo_crd>
//more code here 
<ul>
   @foreach (var item in Model)
   { 
       <li><span>@item.geo_lat </span></li>
       <li><span>AddLocationPin(@item.geo_lat, @item.geo_long, null, 'place 1'); </span> </li>
   } 
</ul>