views:

34

answers:

1

I have the following code in my post action method for Edit.

            JobCardService.Update(viewData.JobCard);
            var js = new JavaScriptSerializer();
            ViewData["Notifications"] = js.Serialize(new {NoteificationType = "Success", Message = "The installtion was successfully updated"});
            return RedirectToAction("Index");

However, on the client, ViewData is null/empty, i.e. this client code

var notifications = eval("<%= ViewData["Notifications"]%>");

renders as

var notifications = eval("");

I'm sure I'm doing something small wrong.

A: 

ProfK - I think (as you'll no doubt be aware) you'll have to parse that json result in javascript once you get into your index view via the redirect. the jquery .getJson() method would seem most appropriate: http://api.jquery.com/jQuery.getJSON/

Also, as you're doing a RedirectToAction, then the context of the ViewData will be lost. In that case, you want to use TempData as a drop in replacement. Below is an example of what you could try:

jim

[edit] - not sure if this would work:

// in the controller
TempData["Notifications"] = js.Serialize(...);

// in the index view
function getMyJsondata() {
    var json = $.getJson('<%=ViewContext.TempData["Notifications"] %>');
}

or as per your amendment to the question, try this:

// alternative in index view
eval("(" + "<%= TempData['Notifications']%>" + ")"); 

give it a go...

adendum: to quote from a previous SO question on Tempdata vs ViewData: http://stackoverflow.com/questions/313572/what-is-tempdata-collection-used-for-in-asp-net-mvc

TempData is used to share data between controller actions. If your controller does a RedirectToAction and the target action needs data (perhaps a particular model instance) to act upon, you can store this data in TempData. Using TempData is similar to storing it in the session, but only for one round-trip. You use TempData when you need to pass data to another controller action rather than a view for rendering.

jim
Thanks @jim, but my problem is now that that ViewData is simply not appearing on the client.
ProfK
ProfK - try using TempData (in the same way), rather than ViewData. TempData is session based, whereas ViewData is linked to that controller action (i.e. the Edit action)
jim
Thanks, but TempData gave me the same issue. I have made master page typed for BaseViewData and moved my notifications collection to that class. I'll recheck TempData later, but for now things are wworking.
ProfK