开发者

ASP.NET MVC Object reference not set to an instance of an object

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:

开发者_JAVA技巧
<%@ 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:

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...


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

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜