首页 > 解决方案 > 如何将字符串从 MVC 传递到 Javascript 以使用 Ajax 执行

问题描述

  public ActionResult GiveTicket(Guid voteId, Guid applyId,string cptcha)
    {       
        //檢查此票選是否允許此登入方式
        var canVoteWay = _voteService.GetVoteWay(voteId);

        string message = string.Empty;
        string loginPath = $"{ConfigurationManager.AppSettings["DomainName"]}/Account/Login?returnUrl={Request.UrlReferrer}";

        //檢查是否已登入
        if (User.Identity.IsAuthenticated && WebLogic.HasValue(canVoteWay, (int)CurrentUser.LoginType))
        {               
            // [驗證圖形驗證碼]
            if (string.IsNullOrEmpty(cptcha) || cptcha != Session["VerificationCode"]?.ToString())
            {
                Response.Write("<script language=javascript> bootbox.alert('圖形驗證碼驗證錯誤,請重新輸入!!')</script>");
                return null;
            }

            //var result = _voteService.GiveTicket(voteId, applyId, CurrentUser.Id, CurrentUser.LoginType);
            Response.Write("<script language=javascript> bootbox.alert('投票成功')</script>");
            return null;              
        }


        message = _voteService.VoteWayString(canVoteWay, "請先登入,才能參與投票!! 投票允許登入的方式:");
        Response.Write("<script language=javascript> if (confirm('" + message + "',callback:function(){})){window.location = '" + loginPath + "'}</script>");
        return null;
    }     

我的ajax代码

 function GiveTicket(applyId) {
        var voteId = $('input[name="Id"]').val();
        var captcha = $('input[name="Captcha"]').val();
        $.ajax({
            url: '@Url.Action("GiveTicket", "Vote")',
            data: { applyId: applyId, voteId: voteId, cptcha: captcha },
            type: 'Get',
            success: function (data) {
                console.log(data);

                //bootbox.alert(data);
            }
        });
    }

就像你看到的那样。我有很多条件。有时我需要向网络客户端传递警报或确认。当我通过确认。如果用户单击是。我需要重定向网址。所以我决定将字符串写入网络客户端。

问题是我如何才能从 MVC 中执行字符串,如警报、确认...

标签: javascriptc#asp.net-mvc

解决方案


您好,希望这篇文章
可以帮助您将字符串传递给使用 viewbag 或 viewModel 进行查看,
然后在此视图中使用 razor 放置重定向逻辑。


推荐阅读