Frens Frens - 5 months ago 19
Ajax Question

Call a method from button click in ASP.net, using controller

am new to ASP.net. Am trying to have a simple page view that has a button and when clicked, this would call a method that is in a controller, to then do more code and computation with c#.

I read posts and tried this but the method does not seem to be called, the debugger never stops in the Controler ClickButton1 method.

My VIEW code



<div>
<input id="Button1" type="button" value="Button 1" onclick="ClickButton1()" />
<input id="Button2" type="button" value="Button 2" onclick="location.href='@Url.Action("Options", "Home")'" />
</div>

<div>
<canvas id="mapCanvas" width="500" height="150" style="border:1px solid #000000;"></canvas>
</div>

<script>
function ClickButton1() {
$.ajax({
type: "POST",
url: '@Url.Action("ClickButton1", "Definition")',
async: true,
success: function (msg) {
ServiceSucceeded(msg);
},
error: function () {
return "error";
}
});
}
</script>





My CONTROLLER



namespace Traveler.Controllers
{
public class DefinitionController : Controller
{
// GET: /<controller>/
public IActionResult Index()
{
return View();
}

// Action click on Button 1
public void ClickButton1()
{
Console.WriteLine("Button 1 Clicked");
}
}
}




Answer Source

Change the input type to button from submit to avoid multiple submit.

Mark you Controllers method as [HttpPost] and try again.

If you are wondering why should you do that, read this:

The [HttpPost] attribute tells the routing engine to send any POST requests to that action method to the one method over the other. This is a type of overloading.

If you are wondering how to mark you Method as a [HttpPost] method, look at this:

[HttpPost]
public void ClickButton1()
{
    Console.WriteLine("Button 1 Clicked");
}

I hope this will help you :)