模型值为null但为什么?

时间:2015-04-01 00:59:06

标签: c# asp.net oop

我一直致力于一个网络应用程序,以便在C#中处理旅行预订,并且已经完全碰到了试图解决这个问题的问题。

尝试打开网页' FlightDB'时,收到以下错误:

An exception of type 'System.NullReferenceException' occurred in App_Web_z0gc0uw3.dll but was not handled in user code

在FlightDB的视图中,Model的值为null。我很确定这是导致错误的原因,但我无法理解原因。

以下是观点:

@model IEnumerable<WebsiteAssignment.Models.FlightsTbl>

@{
    ViewBag.Title = "Choose Flights:";
}

<h2>FlightDB</h2>
<table>

    @foreach (var item in Model) //model = null
    {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.FlightId)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Departing_Airport)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Arriving_Airport)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Departure_Flight_Time)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Return_Flight_Time)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Available_Space)
            </td>
        </tr>
    }
</table>

控制器:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebsiteAssignment.Models;

namespace WebsiteAssignment.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/

        private FlightDBEntities1 db = new FlightDBEntities1();

        public ActionResult Index()
        {
            int currentHour = DateTime.Now.Hour;
            ViewBag.Message = currentHour < 12 ? "Good Morning" : "Good Afternoon";

            return View(db.FlightsTbls.ToList());
        }

        [HttpGet]
        public ActionResult ApplicationPage()
        {
            return View();
        }

        [HttpPost]
        public ActionResult ApplicationPage(Application newApplication)
        {
            var WebsiteAssignment = new List<Application>();

            if (Session["WebsiteAssignment"] != null)
            {
                WebsiteAssignment = (List<Application>)Session["WebsiteAssignment"];
            }

            WebsiteAssignment.Add(newApplication);

            Session["WebsiteAssignment"] = WebsiteAssignment;


            if (ModelState.IsValid)
            {
                return RedirectToAction("FlightDB");
                //return RedirectToAction("Index");
            }
            else
            {
                return View();
            }
        }

        public ActionResult FlightDB()
        {
            return View();
        }

    }
}

如果有人能帮助我理解我会非常感激。差点把我的头发拉过来。

提前感谢您的帮助。

1 个答案:

答案 0 :(得分:4)

您必须传递Model的模型才能获得值。例如:

public ActionResult FlightDB()
{
    return View(new List<WebsiteAssignment.Models.FlightsTbl>());
}

View()有许多重载,其中一个允许您简单地传入模型。然后,MVC框架将搜索与方法名称匹配的视图(在本例中为FlightDB),以便将模型发送到渲染。