Ajax Post 请求成功后重定向到 C# Asp Net MVC 中的页面

Redirecting to a page in C# Aspnet MVC after a successful Ajax Post request

我试图在发出 Ajax Post 请求后重定向到 URL,但我的代码没有重定向

这是我的示例代码。

window.onload = 函数 () { 让 base_url = window.location.protocol + "//" + window.location.hostname + ":" + window.location.port + "/"; // 创建一个基础 url 让 URL = base_url+"api/Teacherdata/AddTeacher"; //创建路径 让表格 = document.forms.new_teacher;

form.onsubmit = processForm;

function processForm() {
    let fname = form.teacherfname;
    let lname = form.teacherlname;
    let salary = form.salary;
    let hiredate = form.hiredate;
    let employeenumber = form.employeenumber;

    var xhttp = new XMLHttpRequest();
        
    xhttp.open("POST", URL, true);
    xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xhttp.send("teacherfname=" + fname.value + "&teacherlname=" + lname.value + "&teacheremployeenumber=" + employeenumber.value + "&teachersalary=" + salary.value + "&teacherhiredate=" + hiredate.value);
    xhttp.onreadystatechange = function () {
        if (this.readyState == 4 && this.status == 200) {
            window.location.href = base_url + "teacher/list";
        }
    };
}

}

要重定向到 mvc 操作方法,您可以使用

window.location.href = "/{controller}/{action}/{params}";

或者,如果您使用 cshtml 编写脚本,您也可以使用

 window.location.href = '@Url.Content("~/{controller}/{action}/{params}")';