Search code examples
c#asp.net-coreasp.net-core-mvctempdata

TempData currently unable to handle this request


How can I fix TempData is not working, page redirects to localhost is currently unable to handle this request. HTTP ERROR 500

What I want to achieve is to create a form that accepts model, and can add multiple data, I want to store the temporary list of model to the TempData before inserting it all to database and I got stuck from this issue. How can I possibly fix this? Am I missing something?

Here is my Startup.cs code:

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
    //some code here

    //services.AddMvc();
    services.AddMvc().AddSessionStateTempDataProvider();
    services.AddSession();
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    //some code here

    app.UseSession();

    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}");
    });
}

Controller code:

[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Create1(BooksViewModel vmodel, Books books)
{
    if (ModelState.IsValid)
    {
        //some code here

        TempData["BooksViewModel"] = books;

        return RedirectToAction(nameof(Entry));
    }
    return View();
}

public IActionResult Entry()
{
    BooksViewModel vmodel = (BooksViewModel)TempData["BooksViewModel"];
    List<BooksViewModel> list = new List<BooksViewModel>();
    list = (List<BooksViewModel>)TempData["BooksViewModelList"];
    if (vmodel != null)
    {
        //some code here
    }
    TempData["BooksViewModelList"] = list;
    return View(list);
}

Entry.cshtml code:

  @model IEnumerable<QnE_Accounting.Models.TransactionsViewModel.BooksViewModel>

<p>
    <a asp-action="Create">Create New</a>
</p>
<table class="table">
    <thead>
        <tr>
              //some code here
            <th></th>
        </tr>
    </thead>
    <tbody>
@foreach (var item in Model) {
        <tr>
            //some code here
            <td>
                <a asp-action="Edit" asp-route-id="@item.Id">Edit</a> |
                <a asp-action="Details" asp-route-id="@item.Id">Details</a> |
                <a asp-action="Delete" asp-route-id="@item.Id">Delete</a>
            </td>
        </tr>
}
    </tbody>
</table>

Solution

  • 500 Errors always comes with the exception details, that should tell you what is wrong! So inspect the exception/inner exception to see why your code is crashing. I would also suggest you to use visual studio breakpoints and inspect the C# expressions (your code) to see it has the values as expected.

    Regarding TempData, In Asp.Net core, you cannot pass complex types in TempData. You can pass simple types like string, int, Guid etc. This is by design.

    If you absolutely want to pass a complex type object between 2 action methods, you have a few options

    1) Serialize your object to a string and pass that.

    var booksString = Newtonsoft.Json.JsonConvert.SerializeObject(books);
    TempData["books"] = booksString;
    return RedirectToAction("Entry");
    

    and in your Entry action, you will read from TempData and deserialize the string back to your object.

    public IActionResult Entry()
    {
        var tempDataStr = TempData["books"] as string;
        // De serialize the string to object
        var books = Newtonsoft.Json.JsonConvert.DeserializeObject<Books>(tempDataStr);
        // Use books
        // to do : return something
    }
    

    2) Persist the data and read it again. You can store the data somewhere and read it again. Here are 2 options to consider.

    • Session state
    • Database table