ASP.NET MVC - Razor - Overloading a button with action, controller, and html attributes

19,097

Write it as an anchor tag instead since you seem to want to redirect users when the button is clicked. You can easily style the anchor to look like a button if you wishes to.

    <a href="@Url.Action("Index", "Home", 
        new { id = Model.FirstorDefault.Id.ToString()})">Submit</a>

And now the "Submit" caption makes no sense as you are now doing a "GET" action instead of a "POST". But if you insist on using a button you could do this:

<input type="button" value="Submit" id="btn1" />

// just replace zero with whatever value you need to use
$("#btn1").click(function () {
    window.location.replace('@Url.Action("about", "Home", new { id = 0 })');
});
Share:
19,097
Ren
Author by

Ren

Areas currently focused on Rust, Python, C# / dotnet Kubernetes and related Cloud-Native Tools Containerized microservices on AWS and Azure Linux and IaC tools such as Terraform and Ansible Recent Certifications CNCF Certified Kubernetes Application Developer (CKAD) Azure Developer Associate AWS Certified Solutions Architect

Updated on June 05, 2022

Comments

  • Ren
    Ren almost 2 years

    I would like to rewrite the below code using a button instead of an ActionLink. Any help would be greatly appreciated. Thanks.

    @Html.ActionLink("Test Link","Index", "Home", new { id = item.id})
    

    Is it possible to write something like the below or is there a better way ? I'm not sure about syntax either, so please feel free to correct it.

    <input type="button" value="Submit" onclick="location.href='@Url.Action("Index", "Home", new { id = @Model.FirstorDefault.Id.ToString()}, null)'" />