简体   繁体   English

如何使用 ASP.NET Core / Razor 通过单击按钮运行在 Razor 页面上编写的 C#?

[英]How do you run C# written on a Razor page from a button click with ASP.NET Core / Razor?

I would like to execute a C# method that I wrote directly on the razor page when a button is clicked on the page.我想在页面上单击按钮时执行我直接在剃须刀页面上编写的 C# 方法。 What I'm finding is if I have the reference to the button on the page, it executes the method on first load but never again when I actually click the button.我发现如果我有对页面上按钮的引用,它会在第一次加载时执行该方法,但在我实际单击按钮时不再执行。 Here's the code:这是代码:

Razor Page C# Reference: Razor 页面 C# 参考:

@functions
{
    int productIndex = 0;

    int AddProduct()
    {
        productIndex = productIndex + 1;
        return productIndex;
    }
}

Button Reference:按钮参考:

 <button type="button" class="btn btn-success" onclick="@AddProduct()" value="New Product" />

I've also tried this reference and got the same result:我也试过这个参考并得到相同的结果:

<input class="btn btn-success" onclick="@AddProduct()" value="New Product"/>

Part 2 question that I have is how do you stop it from executing on page load so it only runs onclick?我的第 2 部分问题是如何阻止它在页面加载时执行,使其仅在单击时运行? I've found references to Page.IsPostBack) but this isn't recognized on the client side, it seems.我找到了对Page.IsPostBack)的引用,但这似乎在客户端无法识别。

This may be a little late but I am just developing a website using ASP.NET Core and Razor pages and this is what I have done to implement C# code behind a button.这可能有点晚了,但我只是在使用 ASP.NET Core 和 Razor 页面开发一个网站,这就是我在按钮后面实现 C# 代码所做的工作。 My button performs a post operation calling the function OnPostGenerateWebName() (the handler name for the button is GenerateWebName ) so the button's post operation will look for and run the function named OnPost<handler name> :我的按钮执行调用函数OnPostGenerateWebName()的发布操作(按钮的处理程序名称是GenerateWebName ),因此按钮的发布操作将查找并运行名为OnPost<handler name>的函数:

First I created a button on the web page ( BusinessDetails.cshmtl file):首先,我在网页上创建了一个按钮( BusinessDetails.cshmtl文件):

 <button type="submit" asp-page-handler="GenerateWebName" class="btn btn-outline-info" id="btnGenerateWebName">Generate Business Web Name</button>

Next I create the handler OnPostGenerateWebName in C# (in the BusinessDetails.cshtml.cs file) which calls another C# function CreateWebName() :接下来,我在 C# 中创建处理程序OnPostGenerateWebName (在BusinessDetails.cshtml.cs文件中),它调用另一个 C# 函数CreateWebName()

  public async Task<IActionResult> OnPostGenerateWebName(string returnUrl = null)
    {
        CreateWebName();

        // all  done
        return Page();
    }


    private void CreateWebName()
    {
        //generate a web name for this business
        if (Business.BusinessName.Length > 0)
        {
            var WebName = Business.BusinessName;
            // remove all special characters, only keep 0-9,a-z,A-Z
            WebName = Regex.Replace(Business.BusinessName, "[^0-9a-zA-Z]+", "");
            // set the new web name
            ModelState.Clear();
            Business.BusinessWebName = WebName;

        }

This function creates a webname from the business name and displays the web name on the form by setting the underlying class model element Business.BusinessWebName .此函数从业务名称创建一个 Web 名称,并通过设置基础类模型元素Business.BusinessWebName在表单上显示 Web 名称。 In order for this to display on the form I had to call ModelState.Clear() .为了让它显示在表单上,​​我必须调用ModelState.Clear()

Hope this helps you in the future.希望这对您将来有所帮助。

It seems as though at this point in time, client-side C# is in development (based off of the comments), and based solely off of the example you provided this is a pure Javascript solution.似乎此时,客户端 C#正在开发中(基于评论),并且仅基于您提供的示例,这是一个纯 Javascript 解决方案。

HTML HTML

<div>
    <button type="button" onclick="AddProduct()">New Product</button>

    <p id="ShowResult1">

    </p>
</div>

jQuery/Javascript jQuery/Javascript

<script>
    var count = 0;

    function AddProduct() {

        count++;

        $("#ShowResult1").text(count);
    }
</script>

I hope this helps.我希望这有帮助。

Years later, but here is what I am doing in 2022:多年后,但这是我在 2022 年所做的事情:

I am using re-usable component which is the _Layout page.我正在使用可重用组件,即 _Layout 页面。

This makes the solution slightly more scalable, in my opinion.在我看来,这使得该解决方案更具可扩展性。

What I have done is make a copy of _Layout, and renamed it _Layout2.我所做的是复制_Layout,并将其重命名为_Layout2。

Difference between _Layout and _Layout2 is literally just "bg-white" vs "bg-danger". _Layout 和 _Layout2 之间的区别实际上只是“bg-white”与“bg-danger”。

Now what is left is to bind buttons, links, inputs - however you like - to call _Layout, and _Layout2 respectively.现在剩下的就是绑定按钮、链接、输入 - 无论你喜欢 - 分别调用 _Layout 和 _Layout2。

I have my html:我有我的html:

 @*This is on the Index.cshtml*@ @page @model IndexModel @{ ViewData["Title"] = "Home page"; } @*Div container to align my two buttons neatly*@ <div class="container"> <div class="row"> @*An option for styling - this one is the default Layout*@ <div class="col"> <form method="post"> <button type="submit" class="btn btn-primary" name="theme" value="_Layout">Blue!</button> @{Layout = Model.Message;} </form> </div> @*Another option - this one simply makes the navbar red*@ <div class="col"> <form method="post"> <button type="submit" class="btn btn-danger" name="theme" value="_Layout2">Red!</button> @{Layout = Model.Message;} </form> </div> </div> </div>

Now, C# code to handle a POST - seeing as I am using buttons:现在,处理 POST 的 C# 代码 - 看到我正在使用按钮:

public class IndexModel : PageModel
{
    private readonly ILogger<IndexModel> _logger;

    public IndexModel(ILogger<IndexModel> logger)
    {
        _logger = logger;
    }
    public string Message { get; set; } = "_Layout";
    public void OnGet()
    {

    }
    public IActionResult OnPost(string theme)
    {
        Message = theme;
        return Page();
    }
}

This code will be called by the html I provided above and toggle between the two _Layout's - _Layout and _Layout2此代码将由我在上面提供的 html 调用,并在两个 _Layout 之间切换 - _Layout 和 _Layout2

(Only added an OnPost() method, and a Message property, the rest is boiler plate code when creating a fresh Razor Page) (仅添加了一个 OnPost() 方法和一个 Message 属性,其余为创建新 Razor 页面时的样板代码)

I hope this makes sense and that I could help someone!我希望这是有道理的,我可以帮助别人!

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

相关问题 如何使用 ASP.NET 内核制作 Razor 页面和 C# 代码框架? - How to do you make both a Razor Page and C# code framework with ASP.NET Core? 如何隐藏和显示 asp.net core razor 页面中未在 c# 中的服务器命令中运行的按钮? - how to hide and show button in asp.net core razor page which are not have run at Server command in c#? ASP.Net剃刀页面-如何将JSON从剃刀页面返回到javascript $ .getJson? - ASP.Net Razor Pages - How do you return json from a razor page to javascript $.getJson? 将值从Button传递回ASP.NET MVC 3 Razor页面的C#控制器 - Pass Value from Button back to C# Controller from ASP.NET MVC 3 Razor Page 如何在ASP.NET C#/ Razor中传递表单后变量? - How do you pass post form variables in ASP.NET C#/Razor? ASP.NET Core 2,在没有 MVC 的情况下使用 Razor 页面单击按钮 - ASP.NET Core 2, button click with Razor pages without MVC 如何使用提交按钮发布 SQL 数据 asp.net c# razor - How do I post SQL data using submit button in asp.net c# razor .split with razor details C#asp.net core - .split with razor details C# asp.net core Razor Page C# ASP.NET Core 获取 Windows 用户名(Windows 身份验证) - Razor Page C# ASP.NET Core get Windows Username (Windows Auth) 从视图路由到 Razor 页面操作 Asp.Net Core 3 - Routing from View to a Razor Page action Asp.Net Core 3
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM