Can I use tempdata messages as jquery alerts?

jewel 1,186 Reputation points
2024-11-03T14:44:57.8966667+00:00
Working with TempData when I'm working on IActionResult . I want to use this tempdata information in alert used in ajax success or error function. Is it possible?
I don't want to use bootstrap alert.

    public IActionResult InserData(tbl_Company np)
    {
        if (ModelState.IsValid)
        {
            var pro = new tbl_Company();
            pro.CompnayName = np.CompnayName;
            pro.ContuctNo = np.ContuctNo;
            _context.tbl_Companies.Add(pro);
            _context.SaveChanges();
            TempData["sms"] = "Data Save";// i want so see this data as message for jquery alert
            return RedirectToAction("Index");
        }
        else
        {
            TempData["sms"] = "Data Not Save";// i want so see this data as message for jquery alert
            return RedirectToAction("Index");
        }
    }

 function addata() {
     var objdata =
     {
         CompnayName: $('#Compnay_Name').val(),
         contuctNo: $('#ContuctNo').val(),
    
     };
     $.validator.unobtrusive.parse($("#my_form"));
     if ($("#my_form").valid()) {
         $.ajax({
             type: 'POST',
             url: '/Company/InserData',
             contentType: 'application/x-www-form-urlencoded; charset=utf-8',
             data: objdata,
             success: function () {
                 alert("Saved") //here i want use tempdata
                 window.location.href = "/Company/Index";
             },
             error: function () {
                 alert("Not Saved") //here i want use tempdata
                 window.location.href = "/Company/Index";
             }
         });
     }
 }
Developer technologies ASP.NET ASP.NET Core
0 comments No comments
{count} votes

Accepted answer
  1. Bruce (SqlWork.com) 77,686 Reputation points Volunteer Moderator
    2024-11-03T16:55:03.57+00:00

    TempData is saved for one request. Your Ajax call does a redirect to index, so this request gets the TempData. After the Ajax call completes, the JavaScript does a another request to index, but now the TempData is empty.

    as the JavaScript ignores the the response data, it not clear why the action does a redirect. It could return json that the JavaScript processed, or as it redirect on the response, it’s not clear why Ajax was used. The form action could just be the action, and index could just display an alert if there was temp data.

    1 person found this answer helpful.
    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Anonymous
    2024-11-04T04:08:23.4366667+00:00

    Hi jewel,

    You need know the following things:

    1. TempData is server-side storage, while AJAX responses operate on the client side. TempData won’t be available in the AJAX callback directly.
    2. You cannot use RedirectToAction in the backend, because ajax cannot handle redirect operation from backend.
    3. No matter the validation is valid or not in server side, RedirectToAction(e.g Ok/Json...) is a successful response for ajax call back. You can return BadRequest to make the response error for ajax, and use .responseText in ajax error function to get the response message.

    A solution is to modify your InserData action to return a JSON response instead of redirecting. This way, you can directly return the TempData message in the response, allowing AJAX to capture it and display it in the alert.

    View:

    <script>
        function addata() {
            var objdata =
            {
                CompnayName: $('#Compnay_Name').val(),
                contuctNo: $('#ContuctNo').val(),
            };
            $.validator.unobtrusive.parse($("#my_form"));
            if ($("#my_form").valid()) {
                $.ajax({
                    type: 'POST',
                    url: '/Company/InserData',
                    contentType: 'application/x-www-form-urlencoded; charset=utf-8',
                    data: objdata,
                    success: function (res) {
                        alert(res) //here i want use tempdata
                        window.location.href = "/Company/Index";
                    },
                    error: function (xhr) {
                        alert(xhr.responseText) //here i want use tempdata
                        window.location.href = "/Company/Index";
                    }
                });
            }
        }
    </script>
    

    Controller:

    public IActionResult InserData(tbl_Company np)
    {
        if (ModelState.IsValid)
        {
            TempData["sms"] = "Data Save";// i want so see this data as message for jquery alert
            return Json(TempData["sms"]);
        }
        else
        {
            TempData["sms"] = "Data Not Save";// i want so see this data as message for jquery alert
            return BadRequest(TempData["sms"]);
        }
    }
    

    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best regards,
    Rena

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.