Vitaliy
Vitaliy

Reputation: 755

RedirectToPage losts route object item content in Razor Pages

I'm trying to redirect to Error page with current data object as parameter:

if (!dataObj.IsValid)
{
    return RedirectToPage("./Error", new { dataObj = dataObj });
}

This object includes a lot of data, I need some properties of it (which are classes types) for Error page, but in Error page handler whole dataObj content have reset to default values (null, 0 etc). How can I pass these data?

Upvotes: 2

Views: 1506

Answers (1)

Mike Brind
Mike Brind

Reputation: 30055

Route values are simple values that you pass in the URL. You can't pass complex objects that way. You can use TempData to pass complex objects for consumption by the next request: https://www.learnrazorpages.com/razor-pages/tempdata

You will need to serialize the object to JSON and probably use Session as a storage mechanism for the data, rather than the default cookie-based storage. I use the following extension methods to serialize and deserialize complex types for use with TempData:

public static void Set<T>(this ITempDataDictionary tempData, string key, T value) where T : class
{
    tempData[key] = JsonConvert.SerializeObject(value);
}

public static T Get<T>(this ITempDataDictionary tempData, string key) where T : class
{
    object o;
    tempData.TryGetValue(key, out o);
    return o == null ? null : JsonConvert.DeserializeObject<T>((string)o);
}

In your OnPost, you would do this:

if (!dataObj.IsValid)
{
    TempData.Set("errors", dataObj);
    return RedirectToPage("./Error");
}

Then in Error:

var errors = TempData.Get<WhateverTypeDataObjIs>("errors");

Upvotes: 3

Related Questions