Maestro00
Maestro00

Reputation: 21

Show toast message by calling from controller

I am using MVC and I want to show message as toast base on my function result from controller. My code is working from one step behind.

Here is My View:

 @(Html.DevExtreme()
               .Button()
               .Icon("check")
               .Hint("Check the User")
               .OnClick("function(e) {CheckUser(e,data,rowIndex) }")
               )

       function CheckUser(e, f, g) {
           console.log(e)
           console.log(f.InsertedUserId)
           console.log(f.AdminUserId)

           $.ajax({
               type: "POST",
               url: '@Url.Action("CheckUser","UserRoleManagement")',
               data: " {AdminUserId: '" + f.AdminUserId + "', InsertedUserId:'" + f.InsertedUserId + "', IsCSOUser: 'False'}",

               contentType: "application/json; charset=utf-8",
               dataType: "html",
               success: function (result) {
                   var a = '@TempData["CheckerResult"]';
                   if (a.toString() == "Succes") {
                       showToast(e)
                   }
                   else {
                       showToast3(e)
                   }

                   console.log(result);
               }
           })
       };

       function showToast(e) {
           console.log('showToast');

           $("#toast").dxToast({

               message: 'Updated succesfully',
               type: 'success',
               displayTime: 3000,
               maxWidth: 500,
               height: "auto",
               animation: { show: { type: 'fade', duration: 400, from: 0, to: 1 }, hide: { type: 'fade', duration: 400, to: 0 } },
               position: { my: 'center bottom', at: 'center bottom', of: window }
           });
           $("#toast").dxToast("show");

       }

       function showToast3(e) {
           console.log('showToast');

           $("#toast").dxToast({

               message: 'Process Failed.',
               type: 'error',
               displayTime: 3000,
               maxWidth: 500,
               height: "auto",
               animation: { show: { type: 'fade', duration: 400, from: 0, to: 1 }, hide: { type: 'fade', duration: 400, to: 0 } },
               position: { my: 'center bottom', at: 'center bottom', of: window }
           });
           $("#toast").dxToast("show");

       }

Here is my Controller:

[HttpPost]
public ActionResult CheckUser(string AdminUserId, string InsertedUserId, bool IsCSOUser)
        {
            RoleGroupRepository rep = new RoleGroupRepository();
            //TempData["Success"] = "User is checked Successfully.";

            SiteSession session = (SiteSession)SessionManager.ReturnSessionObject(SessionKeys.MainSession);

            long CurrentLoggedUserId = session.AdminUserId;

            if (CurrentLoggedUserId == Convert.ToInt64(InsertedUserId))
            {
                TempData["CheckerResult"] = "User check is not Successful.";
                pLogger.INF("User check is not Successful. User can not check by the Inserted User.");
                return Json(new { success = false, responseText = "Fail! User is not checked!" }, JsonRequestBehavior.AllowGet);
            }

            ReturnValuesParser returnValues = rep.CheckUser(AdminUserId, Convert.ToString(CurrentLoggedUserId), IsCSOUser);

            if (returnValues.ReturnCode == 1)
            {
                TempData["CheckerResult"] = "Succes";
                return Json(new { success = true, responseText = "Succes" }, JsonRequestBehavior.AllowGet);
            }
            else
            {
                TempData["CheckerResult"] = "User check is not Successful.";
                pLogger.INF("User check is not Successful" + returnValues.returnDescription_En);
            }

            return Json(new { success = false, responseText = "Fail! User is not checked!" }, JsonRequestBehavior.AllowGet);
        }

What should i change here to show my message base on the TempData["CheckerResult"] result? It is always getting reference one step behind. I logically get the issue but don't know how to resolve.

will be grateful for any response. Cheers

Upvotes: 0

Views: 1587

Answers (1)

David
David

Reputation: 218808

You're examining the value that was present when you first rendered the view:

var a = '@TempData["CheckerResult"]';

But not using anything from the returned result in the AJAX call:

result

Take a look at the page source in your browser and observe how @TempData["CheckerResult"] essentially becomes a hard-coded literal value to your JavaScript code. It's not going to change.

Basically, don't use TempData when you're not returning a view. You're returning JSON, which contains the information you want:

return Json(new { success = true, responseText = "Succes" }, JsonRequestBehavior.AllowGet);

So examine that returned information in your AJAX response handler:

if (result.responseText == "Succes")

You'll also want to change this:

dataType: "html"

to this:

dataType: "json"

Because you're expecting JSON back from the server, not HTML.

Upvotes: 2

Related Questions