ViewData is not passed to View

I am trying to send String

to a 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 am getting is at VP.ViewData["Date"].ToString()

,

An object reference is not set on an object instance.

I was looking for the error and found several articles ( 1 , 2 ). They say that I need to do a null check, but how to set up the controller, ViewData ["date"] will never be null and I would like to keep this logic in the controller.

Also, I found this one , but they instantiate the model in the controller, not the view.

Is there a better way to pass this string other than ViewData? If not, how can I fix this?

+3


source to share


1 answer


Don't use an instance ViewPage

, your view already inherits implicit from this type. Try to just call a property ViewData

on your view, for a sample:

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

      



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

enter image description here

+7


source







All Articles