Home > other >  .Net-Core html form request redirects the page to related View page but with JavaScript website it d
.Net-Core html form request redirects the page to related View page but with JavaScript website it d

Time:07-01

I would like to ask difference between calling Control's action via html FORM and JavaScript. If I use NetCore calls the Action Method and returns View() obj into View page.

But when I call the same Action, webpage stays in the same page.

For example, you have a Employee List page where all employees are listed and wanted to see on of the specific employees details in Emplpoyee Details page.

With html <form method='post' action ='EmployeeDetails'> </form> It works and browser opens the new page.

But with Javascript

function postSelectedCustomerData(path, method = 'post') {

let data = {
    SearchText: 'SearchText1',
    EmpName: '1',
    DealsOnly: true,
    PageNumber: 1
}

fetch("../Employee/EmployeeDetailsPost", {
    method: "POST",
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(data)
   }).then(res => {
    console.log("Request complete! response:", res);
 });
}

NOTE: I know I can redirect the page from fetch Return with window.location.href. But I want to know is there any way i can call action method with JavaScript and return to the action Method page?

CodePudding user response:

When you use standard <form> framework functionality, the server posts back to the client an HTTP response that's being interpreted by the browser as a new web page to be loaded.

When you skip this using a simple javascript fetch, the handling of the response it's all up to you. Just from a DOM point of view (let's suppose you only get '200' response!) you should identify the parent of the existing tree that will be replaced, remove said tree, insert the new one from the response.

fetch("../Employee/EmployeeDetailsPost", {
    method: "POST",
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(data)
    }).then(res => {
        let parent = document.getElementById('parent');
        let root = document.getElementById('root');
        root.remove();
        parent.append(res);
    });
}
  • Related