Search code examples
javascriptjqueryasp.net-mvcrazor

MVC/JavaScript/Razor - How to open a new View from a button


I'm working in a .Net framework using the MVC pattern. I have a link (that works) that looks like this:

<li><a href="@Url.Action("HomePage", "Home")">Main Page</a></li>

In the above link, the "HomePage" is the name of the .cshtml page and there is a method in the controller with the same name that returns the view. The second parameter, "Home", is the subfolder under Views where the .cshtml page is located.

Now, in a different section of the same view, I have a button that should navigate to the same location when clicked. It looks like this:

<input type="button" class="navigationButtons" id="btnHome" value="Main Page" />

Because I am using a .css style sheet for the navigationButtons, I would really LOVE to put the code to go the the Main Page from the button in the JavaScript. So, I've created a jQuery variable and binded it to the .on("click", onHome) event. I have the following method:

onHome = function () {
    var url = '@Url.Action("HomePage", "Home")';
    window.location.href = url;
}

I've also tried window.open("HomePage", "Home"); Along with anything else I could find, to no avail. Important: I do not want the view to open in a new window; it is supposed to open exactly as it does in the link (which displays the view inside the framework view, like an embedded view under the Main Menu which belongs to the Main application page).

I've learned that if I use a button type instead of an input type in the html that I can include a link for onClick but I'm having trouble with that as well. It appears all examples contain a complete url. But I'm trying to open a view in the framework. I do not have a complete url.

Does anybody have any ideas on how to make this type of navigation from JavaScript? If not, or there is a better way in the html, then I am eager to get a response.


Solution

  • Just add the class in tag.

    <a href="@Url.Action("HomePage", "Home")" class="navigationButtons" autocomplete="off" data-loading-text="Loading Main Page...">Main Page</a>