6

I'm trying to add a button on my ASP.NET page. I have experience with Windows forms and I know how to link a click event to a button, but in ASP.NET MVC this link is different.

How to make this link correctly so that when I click the button, the click event written in my c# source to be triggered?

1
  • 1
    ASP.NET MVC doesn't have "events" in the same way. WebForms does, but not MVC. In MVC, you can cause a button click to trigger a controller action method (either via a hyperlink or by submitting a form, or triggering an AJAX request which goes to the URL of the action). I suggest you study Microsoft's introductory ASP.NET MVC tutorial which will introduce you to the basic concepts and also the ways of doing standard tasks such as this. Commented May 1, 2020 at 13:43

2 Answers 2

12

You need create a tag in cshtml file as

<a class="btn btn-primary" href="@Url.Action("YourAction","YourController")">Click</a>

And create method to handle click in controller c# as

public ActionResult YourAction()
{
    //C# code here
}
Sign up to request clarification or add additional context in comments.

Comments

3

If you need to do it by passing parameters, first of all add the button in cshtml file

<a class="btn btn-primary" href="@Url.Action("ActionName", "ControllerName", new{ parameter = "value"})">Click here</a>

And finally in the controller create a method

public ActionResult ActionName(string parameter){
       //Your code here
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.