tags:

views:

684

answers:

4

I'm a .NET and MVC newbie, and learning it for the first time after suffering too long with ASP, and it's about time I converted over to make my job of building web applications that much easier.

I've been going through Stephen Walther's helpful video tutorials to get my head around most things, and I'm making good progress thus far. Where I've come unstuck is creating a details page for a record in my application, ConversationApp. Listing data and inserting new data is working perfectly, but everytime I go to view the details page for any specific record I receive the error message "Object reference not set to an instance of an object".

URL being passed to the controller is: /Home/Details/X (where X is unique ID for the record)

I would appreciate any help to get me past what is likely a very stupid mistake of mine or an oversight.

Here's where I am so far, code wise:

HomeController.CS

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using ConversationApp.Models;

namespace ConversationApp.Controllers
{
public class HomeController : Controller
{

    private conversationDBEntities _entities = new conversationDBEntities();

    //
    // GET: /Home/

    public ActionResult Index()
    {
        return View(_entities.conversation.ToList());
    }

    //
    // GET: /Home/Details/5

    public ActionResult Details(int id)
    {

        return View();
    }

    //
    // GET: /Home/Create

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

    //
    // POST: /Home/Create

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Create([Bind(Exclude="conversation_id")]conversation conversationToCreate)
    {
        try
        {
            // TODO: Add insert logic here
            _entities.AddToconversation(conversationToCreate);
            _entities.SaveChanges();
            return RedirectToAction("Index");
        }
        catch
        {
            return View();
        }
    }

    //
    // GET: /Home/Edit/5

    public ActionResult Edit(int id)
    {
        return View();
    }

    //
    // POST: /Home/Edit/5

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Edit(int id, FormCollection collection)
    {
        try
        {
            // TODO: Add update logic here

            return RedirectToAction("Index");
        }
        catch
        {
            return View();
        }
    }
}
}

Details.aspx

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

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
Details
</asp:Content>

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

<h2>Details</h2>

<fieldset>
    <legend>Fields</legend>
    <p>
        conversation_name:
        <%= Html.Encode(Model.conversation_name) %>
    </p>
    <p>
        conversation_owner:
        <%= Html.Encode(Model.conversation_owner) %>  
    </p>
    <p>
        conversation_description:
        <%= Html.Encode(Model.conversation_description) %>
    </p>
    <p>
        conversation_homeurl:
        <%= Html.Encode(Model.conversation_homeurl) %>
    </p>
</fieldset>
<p>

    <%=Html.ActionLink("Edit", "Edit", new { id=Model.conversation_id }) %> |
    <%=Html.ActionLink("Back to List", "Index") %>
</p>

Error message for /Home/Details/X (where X is unique ID for record)

Server Error in '/' Application.
--------------------------------------------------------------------------------

Object reference not set to an instance of an object. 
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

Source Error:

Line 13:         <p>
Line 14:             conversation_name:
Line 15:             <%= Html.Encode(Model.conversation_name) %>
Line 16:         </p>
Line 17:         <p> 

Source File: c:\Users\Michael Harris\Documents\Visual Studio 2008\Projects\ConversationApp\ConversationApp\Views\Home\Details.aspx    Line: 15 

Stack Trace: 

[NullReferenceException: Object reference not set to an instance of an object.]
ASP.views_home_details_aspx.__RenderContent2(HtmlTextWriter __w, Control parameterContainer) in c:\Users\Michael Harris\Documents\Visual Studio 2008\Projects\ConversationApp\ConversationApp\Views\Home\Details.aspx:15
System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer, ICollection children) +256
System.Web.UI.Control.RenderChildren(HtmlTextWriter writer) +19
System.Web.UI.Control.Render(HtmlTextWriter writer) +10
System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer, ControlAdapter adapter) +27
System.Web.UI.Control.RenderControl(HtmlTextWriter writer, ControlAdapter adapter) +99
System.Web.UI.Control.RenderControl(HtmlTextWriter writer) +25
ASP.views_shared_site_master.__Render__control1(HtmlTextWriter __w, Control parameterContainer) in c:\Users\Michael Harris\Documents\Visual Studio 2008\Projects\ConversationApp\ConversationApp\Views\Shared\Site.Master:26
System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer, ICollection children) +256
System.Web.UI.Control.RenderChildren(HtmlTextWriter writer) +19
System.Web.UI.Control.Render(HtmlTextWriter writer) +10
System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer, ControlAdapter adapter) +27
System.Web.UI.Control.RenderControl(HtmlTextWriter writer, ControlAdapter adapter) +99
System.Web.UI.Control.RenderControl(HtmlTextWriter writer) +25
System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer, ICollection children) +134
System.Web.UI.Control.RenderChildren(HtmlTextWriter writer) +19
System.Web.UI.Page.Render(HtmlTextWriter writer) +29
System.Web.Mvc.ViewPage.Render(HtmlTextWriter writer) +59
System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer, ControlAdapter adapter) +27
System.Web.UI.Control.RenderControl(HtmlTextWriter writer, ControlAdapter adapter) +99
System.Web.UI.Control.RenderControl(HtmlTextWriter writer) +25
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1266

--------------------------------------------------------------------------------
Version Information: Microsoft .NET Framework Version:2.0.50727.4918; ASP.NET  
Version:2.0.50727.4918
+1  A: 

In your Details action method on the controller you are not passing the model back to the view.

public ActionResult Details(int id)
{
    // get model object

    return View(//pass model object to view here);
}
aherrick
A: 

Your problem is in


return View(_entities.conversation.ToList());

Your View is simply your page. The View() normally is the path of the page you want to display. If you pass it without parameters ASP will get the default route based on your controller, In this case it will be redirected to Home/Index.aspx or Default.aspx depending on your routing options.

If you want to pass data to your view, you should use the ViewData hash. That hash is available on the controller and on the page side.

Ex:



Controller Code:

public ActionResult Index()
    {
        List<string> li = new List<string>();
        li.Add("test");
        ViewData["myList"] = li;
        return View();
    }

Page Code:

<div>
<%
   List<string> li = (List<string>)ViewData["myList"];
   foreach(string str in li)
   {
%>
    <p><%= str %></p>
<%
}
%>
</div>
Freddy
+1  A: 

It doesn't look like you're passing any data to the Details view:

public ActionResult Details(int id)
{
   return View();
}

Retrieve your model class from your repository and pass it to the view:

return View(conversation);
krohrbaugh
A: 

Thanks everyone for that superquick help, and those hints pointed me in the right direction. I wrongly assumed that the HomeController would have been smart enough to determine exactly what I wanted it to display after creating the view.

Those clues lead me to: http://www.asp.net/learn/MVC/tutorial-26-cs.aspx

Which after some reading gave me the answers I sought.

Here's the specific part of HomeController.CS which shows how I got it working:

 // GET: /Home/Details/5

    public ActionResult Details(int id)
    {
        var conversationToView = (from c in _entities.conversation
                                  where c.conversation_id == id
                                  select c).FirstOrDefault();
        return View(conversationToView);
    }

As aherrick noted, I was not passing the model back. conversationToView grabs the ID of the record who's details you wish to view, and passes that information to the return view action to retreive the desired result.

At the same time, I was also able to get the answer on how to perform an edit properly as well from the tutorial I found thanks to the above feedback. It's still not submitting edited information, but one step at a time.

Once again, thanks to everyone who responded so dammed quickly to this. It's been racking my brains for days.

thewinchester