通过 HTML 按钮调用 C# 函数 [英] Calling a C# function by a HTML button

查看:36
本文介绍了通过 HTML 按钮调用 C# 函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做的是通过按钮调用函数.

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?

注意:我没有使用 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,如果名称不同,则必须更改 url:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆