ASP。NET MVC对象引用没有设置为对象的实例

时间:2021-09-15 16:55:58

I saw a similar question here on SO but I believe mine differs a little a bit.

我在这里也看到了类似的问题,但我相信我的观点有所不同。

OK, so I have a simple view here:

我有一个简单的观点

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<RootFinder.Models.QuadCalc>" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
Polynomial Root Finder - Quadratic
</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
    <h2>Quadratic</h2>

    <%= Html.BeginForm("Quadratic", "Calculate") %>
    <% { %>
    <div>
        a: <%= Html.TextBox("quadAValue", Model.quadraticAValue) %>
        <br />
        b: <%= Html.TextBox("quadBValue", Model.quadraticBValue) %>
        <br />
        c: <%= Html.TextBox("quadCValue", Model.quadraticCValue) %>
        <br />
        <input type="submit" id="quadraticSubmitButton" value="Calculate!" />
        <br />
        <p><%= Model.x1 %></p>
        <p><%= Model.x2 %></p>
    </div>
    <% } %>
</asp:Content>

And my controller here:

和我这里的控制器:

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

namespace RootFinder.Controllers
{
    public class CalculateController : Controller
    {
        //
        // GET: /Calculate/

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

        [AcceptVerbs(HttpVerbs.Get)]
        public ViewResult Quadratic()
        {
            return View();
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ViewResult Quadratic(QuadCalc newQuadCalc)
        {
            return View(newQuadCalc);
        }

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

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

Now, upon loading my Get version of the Quadratic view, I get the following message from VS2010:

现在,在加载我的Get版本的二次视图时,我从VS2010中得到以下信息:

Object reference not set to an instance of an object

对象引用没有设置为对象的实例

Now, I kind of understand the message in it of itself, but isn't it a bad thing to create a new object of a class within the View itself? Which is why I was trying to handle this in the Controller for the Post only.....

现在,我有点理解其中的消息本身,但是在视图本身中创建一个类的新对象不是一件坏事吗?这就是为什么我试图在控制器中处理这个问题的原因。

Hmm...

嗯…

1 个解决方案

#1


1  

Same as you do in your Post action, but in the Get you pass a new fresh initialized QuadCalc model to the view

与您在Post操作中所做的相同,但是在Get中,您将一个新的初始化的QuadCalc模型传递给视图

[AcceptVerbs(HttpVerbs.Get)]
public ViewResult Quadratic() {
    return View( new QuadCalc() );
}

#1


1  

Same as you do in your Post action, but in the Get you pass a new fresh initialized QuadCalc model to the view

与您在Post操作中所做的相同,但是在Get中,您将一个新的初始化的QuadCalc模型传递给视图

[AcceptVerbs(HttpVerbs.Get)]
public ViewResult Quadratic() {
    return View( new QuadCalc() );
}