从javascript调用c#方法进行重定向

Call c# method from javascript for a redirect

本文关键字:重定向 方法 javascript 调用      更新时间:2023-09-26

我有一个c#方法来重定向

[UIAuthentication()]
[UIMethod("cancelredirect", "mth"), UIMethodGroup("employeradmin")]
public void CancelRedirect(RequestContext Context)
{
  Context.Redirect(string.Format("View.mth?EmployerID={0}", _employerID));
}

从这里我做了一个javascript函数,它被调用,如果取消按钮在一个表单上被按下。

function getCancel() {
    var confirmCancel = confirm('Are you sure you want to cancel?');
    if(confirmCancel)
    {
      //redirect here
    }
    else
    {
    return false;
    }
    };
<input type="submit" id="Cancel" value="Cancel" name="Cancel" class="input_button" onclick="return getCancel();"/>

我只是想知道你如何从javascript调用c#方法来重定向到页面视图。我不是100%确定如何做到这一点,因为我从来没有做过一个这些之前。谢谢你提供的任何帮助

实际上你的问题应该是:"如何从java-script调用操作方法?"

假设你的控制器类名:EmployeeController

if(confirmCancel)
{
  document.location = = '/Employee/CancelRedirect';
}

请通过以下链接了解更多信息:如何在JavaScript/jQuery中重定向到另一个网页?

当你通过ajax调用server方法时,你不能做重定向,因为响应处理程序不是页面。

如果您调用CancelRedirect的目的只是为了获取一个变量,则从服务器端获取EmployerID

您可以通过Ajax获得EmployerID,当前端获得EmployerID时,只需重定向:

window.location = "/View.mth?EmployerID=xxxx";
也许你应该把ajax的async属性改成false

try with ajax:

if(confirmCancel)
{
var url = '/Employee/CancelRedirect';
            $.ajax({
                url: url,
                type: 'POST',
                cache: false,
                data :{ valeur : if you want to send a value }
            })
}