Travis Heeter
Travis Heeter

Reputation: 14054

ViewData not being passed to View

I'm trying to send a String to the controller, via AJAX, and use it in a View that will be returned by the Controller:

Index.cshtml

<div id="apts"></div>
<script>
    $(document).ready(function(){
        $.post("/Apt",{"Date": "05/29/2015"},function(response){
            $("#apts").html(response);
        });
    });
</script>

Controller.cs

...
public ActionResult Apt()
{
    String date = DateTime.Today.ToString("MM/dd/yyyy");
    if (!String.IsNullOrEmpty(Request.Form["Date"]))
    {
        date = Request.Form["Date"];
    }
    ViewData["Date"] = date;
    return PartialView("~/Shared/_DisplaySection.cshtml");
}

_DisplaySection.cshtml

@inherits System.Web.Mvc.WebViewPage
@using System.Web.Mvc
@using MySite.Models
@{
    ViewPage VP = new ViewPage();
    // error is here: Object reference not set to an instance of an object.
    String date = VP.ViewData["Date"].ToString();
    MySite.Models.DisplaySection DW = new DisplaySection(date); 
}

@foreach(var a in DW.data)
{
    <div>@a["name"]</div>
}

The error I'm getting is on VP.ViewData["Date"].ToString(),

Object reference not set to an instance of an object.

I searched for the error and found a couple of articles (1, 2). They say I need to do a null check, but the way the controller is set up, ViewData["date"] should never be null, and I'd like to keep that logic in the Controller.

Also, I found this, but they are creating an instance of the model in the Controller, rather than the View.

Is there a better way to pass this String besides ViewData? If not, how can I fix this?

Upvotes: 3

Views: 4627

Answers (1)

Felipe Oriani
Felipe Oriani

Reputation: 38598

Do not instance the ViewPage, your view already inherits from this type implicity. Try just call ViewData property in your view, for sample:

String date = ViewData["Date"].ToString();

AS you cna see in the controller base class from asp.net mvc, when you return a view or partialView, the controller pass the ViewData property from controller to ViewData property of View/PartialView result.

enter image description here

Upvotes: 8

Related Questions