【问题标题】:Show toast message by calling from controller通过从控制器调用显示 toast 消息
【发布时间】:2020-03-04 15:08:22
【问题描述】:

我正在使用 MVC,我想根据控制器的函数结果将消息显示为 toast。 我的代码落后了一步。

这是我的观点:

 @(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");

       }

这是我的控制器:

[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);
        }

我应该在此处更改什么以根据 TempData["CheckerResult"] 结果显示我的消息?它总是落后一步。我在逻辑上得到了这个问题,但不知道如何解决。

将不胜感激任何回应。干杯

【问题讨论】:

    标签: javascript ajax asp.net-mvc model-view-controller toast


    【解决方案1】:

    您正在检查首次渲染视图时存在的值:

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

    但不使用 AJAX 调用中返回结果中的任何内容:

    result
    

    查看浏览器中的页面源代码,观察@TempData["CheckerResult"] 本质上如何成为 JavaScript 代码的硬编码文字值。它不会改变。

    基本上,当您不返回视图时不要使用TempData。您正在返回 JSON,其中包含您想要的信息:

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

    因此,请检查您的 AJAX 响应处理程序中返回的信息:

    if (result.responseText == "Succes")
    

    您还需要更改此设置:

    dataType: "html"
    

    到这里:

    dataType: "json"
    

    因为您希望从服务器返回 JSON,而不是 HTML。

    【讨论】:

    • 亲爱的@David 非常感谢您的大力帮助,您在 5 分钟内解决了我的问题。我只是一个用MVC和js编码的新手。谢谢大师!
    • 您还有什么建议可以让我将 responseText 传递到 toast 中显示吗?
    • @Maestro00:这是一个和其他任何值一样的值。您可以将其作为参数传递给函数调用,使用它来设置属性等。
    猜你喜欢
    • 2012-07-21
    • 1970-01-01
    • 2015-02-12
    • 2014-05-06
    • 1970-01-01
    • 2011-12-09
    • 2014-07-04
    • 1970-01-01
    相关资源
    最近更新 更多