@foreach不适合模特

时间:2017-03-14 09:26:46

标签: asp.net asp.net-mvc

我今天试图给ASP.NET一个镜头并用一个名为navigation的表创建一个简单的数据库。当我将数据从控制器发送到视图但是我注意到我可以使用@ model.name但它不会让我在模型上使用foreach循环而我无法找出原因。

这是代码

using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using WebApp_OpenIDConnect_DotNet.Models;

namespace WebApp_OpenIDConnect_DotNet.Controllers
{
    public class navigationsController : Controller
    {
        private edulyEntities db = new edulyEntities();

        // GET: navigations
        public ActionResult ShowMenu()
        {
            return View(db.navigation.ToList().OrderBy(n => n.nav_order));
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}

查看:

@model IEnumerable<WebApp_OpenIDConnect_DotNet.Models.navigation>

@foreach (var item in Model)
{
    <li>
        <a href="@Url.Action(Model.action, Model.controller)" class="dont-break-out">
            <i class="@Model.glyphicon_text"></i>
            <span class="smScreenHideText">@Model.name</span>
        </a>
    </li>
}

数据库表

 public partial class navigation
{
    public int id { get; set; }
    public string name { get; set; }
    public int nav_order { get; set; }
    public string glyphicon_text { get; set; }
    public string controller { get; set; }
    public string action { get; set; }
}

1 个答案:

答案 0 :(得分:3)

如果glyphicon_textWebApp_OpenIDConnect_DotNet.Models.navigation类中的属性,那么您应该更新foreach内的代码,如下所示:

@foreach (var item in Model)
{
   <li>
     <a href="@Url.Action(Model.action, Model.controller)" class="dont-break-out">
        <i class="@item.glyphicon_text"></i>
        <span class="smScreenHideText">@item.name</span>
     </a>
   </li>
}

请注意,我已将@Model替换为@item,因为您现在位于foreach的范围内,并且您已宣布item> The following restricted PHP modes have non-empty values: > [error] open_basedir and disable_functions. This configuration is > incompatible with drush. Please check your configuration settings in > /opt/cpanel/ea-php56/root/etc/php.ini or in your drush.ini file; see > examples/example.drush.ini for details. is_dir(): open_basedir > restriction in effect. [warning] > File(/usr/share/drush/commands) is not within the allowed path(s): > (/home/:/usr/lib/php:/usr/local/lib/php:/usr/local/bin:/usr/share/drush:/usr/share/drush/commands:/etc:/tmp) > preflight.inc:518 PHP configuration : > /opt/cpanel/ea-php56/root/etc/php.ini > /home/username/.drush/drush.ini PHP OS : Linux Drush script : /usr/local/bin/drush Drush > version : 8.1.9 Drush temp directory : /tmp Drush > configuration : Drush alias files : 内的对象从控制器传递的集合。