Home > Mobile >  Error when trying to redirect from _Layout page in ASP.NET Core MVC Razor
Error when trying to redirect from _Layout page in ASP.NET Core MVC Razor

Time:12-07

I'm fairly new to .NET Core having worked on older .NET versions like Windows forms. I have a nav bar set up in my _Layout page which I want to use to redirect to other Razor pages.

For example I have a Home page (index.cshtml) in a folder called Home off of my Views folder. If I want to select Customer Search option from the nav bar I use an onclick event which calls the function below.

function SearchClick() {
    window.location.href = "CustomerSearchView.cshtml";
    return false;
}

The CustomerSearchView is in a CustomerSearch folder below the Home folder in Views. There is also a CustomerSearchController with the code

public IActionResult Index()
{
    return View();
}

If I try to add the path into the browser such as https://localhost:7022/CustomerSearchView.cshtml I get the error

This localhost page can’t be found - no webpage was found for the web address: https://localhost:7022/CustomerSearchView.cshtml

I have tried all sort of variations using the full path with Views/CustomerSearch and others but get the same error.

I'm not familiar with the routing procedure and I'm not sure what mistake I'm making and I thought it would save time to ask and would be really happy if someone could point it out.

CodePudding user response:

try this

function SearchClick() {
    window.location.href = "/CustomerSearch/Index";
    return false;
}

CodePudding user response:

I fixed the problem by correcting the routing and adding the following code to my program.cs

app.MapControllerRoute(
    name: "customersearch",
    pattern: "{controller=CustomerSearchController}/{action=Index}/{id?}",
    defaults: new { controller = "CustomerSearchController", action = 
"Index" });

When adding any new views with controllers simply add the equivalent routing code for it to make it visible to the project.

  • Related