3

I am using jquery ajax to post some data to server, save data on the server in TempData and then redirect user to different action.

    [HttpPost]
    public async Task<IActionResult> GetDocument(SearchFiltersModel filters)
    {
        var model = await _service.GetDocument(filters);
        TempData["Detail"] = model;
        return Json("document/detail/" + model.DocumentID)
    }

    [HttpGet]
    public IActionResult Detail()
    {
        // getting error at line below. 
        /// ArgumentNullException: Value cannot be null. Parameter name: dictionary

        var model = TempData["Detail"] as DocumentModel;            
        return View(model);
    }

  $('btn').click(function(){

    $.ajax({
        type: 'POST',
        data: filters, 
        url: 'document/getdocument'
    })
       .done(function (response) {
           window.location = response;
       })
  })

However when Detail action method gets invoked, TempData["Detail"] is null. Why TempData is lost across action methods.

(There is valid reason im doing ajax post on button click rather than form post, but thats irrelevant here)

LP13
  • 30,567
  • 53
  • 217
  • 400
  • I'm not sure why, but you can work around it by using Session instead of TempData. – Rono Oct 28 '16 at 18:19
  • session does work. but i wanted to know why tempdata is not working. ( tempdata is nothing but session i think) – LP13 Oct 28 '16 at 18:30
  • @JamesP yes tempdata will delete the object `AFTER` it reads. In this case the object is not available to read across ajax post – LP13 Oct 28 '16 at 18:39
  • The whole point of ajax is to stay on the **same** page. Why are your using ajax if you want to redirect. Just get it in the GET method based on the ID. –  Oct 28 '16 at 21:26
  • Maybe because you aren't using keep function. Look this link: http://stackoverflow.com/questions/21252888/tempdata-keep-vs-peek – Marcos Magalhães Feb 02 '17 at 01:20

0 Answers0