开发者

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 r开发者_高级运维eference here?


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();
}


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

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜