简体   繁体   English

使用控制器从ASP.net中的按钮单击调用方法

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

am new to ASP.net. 是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#. 我试图使用一个带有按钮的简单页面视图,然后单击该按钮,这将调用控制器中的方法,然后使用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. 我阅读了文章并尝试了此方法,但似乎未调用该方法,调试器永远不会在Controler ClickButton1方法中停止。

My VIEW code 我的VIEW代码

 <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"); } } } 

Change the input type to button from submit to avoid multiple submit. 将输入类型从提交更改为按钮,以避免多次提交。

Mark you Controllers method as [HttpPost] and try again. 将您的Controllers方法标记为[HttpPost]然后重试。

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. [HttpPost]属性告诉路由引擎将对那个操作方法的任何POST请求发送到另一个方法。 This is a type of overloading. 这是一种重载。

If you are wondering how to mark you Method as a [HttpPost] method, look at this: 如果您想知道如何将Method标记为[HttpPost]方法,请查看以下内容:

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

I hope this will help you :) 我希望这能帮到您 :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM