通过HTML按钮调用C#函数 [英] Calling a C# function by a HTML button
问题描述
我想做的就是通过按钮调用函数.
What I’m trying to do is to call function by a button.
我会给你一个简单的代码,不起作用!:
i'll leave you with a simple code that doesn't work!:
@{
protected void print()
{
@<p>WELCOME!</p>
}
}
<form>
<button onclick="print" value="CLICK ME"/>
</form>
关于如何完成上面代码中的工作的任何想法吗?
any idea on how to accomplish what im trying to do in the code above?
注意:IM不使用MVC
推荐答案
您不能这样做,它不是ASP.NET WebForms
.
You can't do it like this.It is not ASP.NET WebForms
.
因此,如果要在Razor中的按钮单击"上执行C#函数,则必须可以创建Controller
,然后当用户单击按钮时,必须可以调用一个javascript函数,然后它将ajax请求发送到您的控制器,然后获取数据(如果有数据)并显示.
So if you want to Execute a C# function on Button click in Razor, you must could create a Controller
,then when user clicks a button you must can call a javascript function and it sends an ajax request to your controller then get the data (if there is data) and display it.
更新:这是有关如何执行此操作的另一个简单示例:
Update: Here is an alternative simple sample about how to do this:
在您的控制器中添加此方法:
In your Controller Add this Method:
public ActionResult GetMessage()
{
string message = "Welcome";
return new JsonResult {Data = message,JsonRequestBehavior = JsonRequestBehavior.AllowGet};
}
在您的视图(HTML)中:
And in your View (HTML):
<input type="button" onclick="GetMessage()" value="Get Message"/>
<p></p>
JavaScript:
JavaScript:
function GetMessage() {
$.get("/Home/GetMessage", function (data) {
$("p").html(data);
});
}
别忘了导入jQuery库:
And don't forget to import jQuery library:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
PS:我假设您的控制器名称为HomeController,如果名称不同,则必须更改网址:
PS: I assume your Controller name is HomeController, you must change the url if it has different name:
$.get("/{Controller-Name}/{Action-Name}", ...)
这篇关于通过HTML按钮调用C#函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!