P.Brian.Mackey
P.Brian.Mackey

Reputation: 44275

nullreferenceexception when accessing ViewData

Controller

    public class DashboardController : Controller
    {
        //
        // GET: /Dashboard/

        public ActionResult Index()
        {
            ViewData["PartnerID"] = GetPartnerID();
            return View();
        }

        public ActionResult OutboundTransfers()
        {
            var partnerId = ViewData["PartnerID"].ToString();//NULL EXCEPTION
            InventoryEntities context = new InventoryEntities();
            var result = context.GetOutboundTransfers(partnerId);
            //var result = context.GetOutboundTransfers("3000017155");

            return View(result);
        }

        private static string GetPartnerID()
        {
            return "3000017155";
        }

    }
}

View (Dashboard/Index)

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

    <h2>Index</h2>
    <%= Html.Action("OutboundTransfers")%>
</asp:Content>

I am a beginner to MVC 2. I read the ViewData should be accessible to the partial view (OutboundTranfers.ascx) as a copy. So, why do I get a null reference here?

Upvotes: 2

Views: 3619

Answers (2)

Kirk Woll
Kirk Woll

Reputation: 77546

ViewData is presumably not null -- ViewData["PartnerID"] is null. (the item is not in the ViewData) Also, you set the PartnerID data in one action, and fetch it in the other. ViewData is not preserved across requests/actions.

(Moved out of comments into an answer...)

Upvotes: 1

JMP
JMP

Reputation: 7834

Instead of setting ViewData["PartnerID"] in Index(), try creating a constructor for your controller and setting the value there like so:

public DashboardController()
{
    ViewData["PartnerID"] = GetPartnerID();
}

Upvotes: 2

Related Questions