lebron Brian
lebron Brian

Reputation: 5

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

I am trying to make a redirect to URL after making an Ajax Post request but my code is not redirecting

Here is my sample code.

window.onload = function () { let base_url = window.location.protocol + "//" + window.location.hostname + ":" + window.location.port + "/"; // creating a base url let URL = base_url+"api/Teacherdata/AddTeacher"; //creating a path let form = 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";
        }
    };
}

}

Upvotes: 0

Views: 563

Answers (1)

Hitesh
Hitesh

Reputation: 36

for redirecting to mvc action method you can use

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

alternatively if you are writing your script in cshtml you can also use

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

Upvotes: 1

Related Questions