Share via


How to Pass TempData to an ajax call mvc 5

Question

Tuesday, October 27, 2020 8:41 PM

I have created a TempData in my controller

TempData["Ids"] = someIds.ToArray();

now I want to pass this tempdata to my ajax call 

  $('#oldemp').change(function() {          
            var Ids = $('#old option:selected').val();
            var emp=  '@TempData["Ids"]';>This line is not empty
            var newData = {  oldId:Ids,Ids:emp };
            $.ajax({
                url: '@Url.Action("emptest")',
                type: "GET",
                data: newData,
                cache: false,
                success: function (data) {
                    debugger;
                    $('#partialPlaceHolder').html(data);
                },
                error:function(xhr) {
                    alert(xhr.status + " " + xhr.error);
                }
            });

Any help will be appreciated.

All replies (6)

Tuesday, October 27, 2020 11:17 PM âś…Answered

Thanks for the response but the value is null in the ajax call whiles the controller value is not null

You needed to set the value on the server.   The use of TempData might indicate other issues with the design where your expectation is not how the MVC works.


Tuesday, October 27, 2020 8:56 PM

JSON serialize the data.   

var emp = @Html.Raw(Json.Encode(TempData["Ids"]));

Tuesday, October 27, 2020 9:02 PM

Hi

Thanks for the response but the value is null in the ajax call whiles the controller value is not null


Tuesday, October 27, 2020 9:05 PM

as this is part of the original render, the controller action for the view needs to set it.

also as you are doing a form post, it can not be an array, it needs to be a scaler value.


Tuesday, October 27, 2020 9:07 PM

Thanks. I will keep you posted


Wednesday, October 28, 2020 2:05 AM

Hi 

Thanks. Got it working. I was setting it at the wrong place instead of at the Index