在剃须刀页面中动态更改按钮标签文本

Change button label text dynamically in razor pages

我在 ASP.NET 核心 Web 应用程序中使用 Razor Pages。

我想从代码隐藏更改按钮文本。即使我在 Html 标记中添加 runat="server",我也无法访问 *.cshtml.cs 文件中的按钮。

此外,我无法在 razor 页面中使用 <asp:button>。有什么办法可以不使用 javascript 方法吗?

<input type="submit" value="Create" class="btn btn-primary"/>

MyPage.cshtml.cs

public IActionResult OnGet(Guid id)
{
if(id == Guid.Empty) //Make button create
else // make it update
}

.net core 中的 Razor 页面与经典的 aspx 页面有很大不同。 one from MS 中有许多不错的介绍文章。使用您的问题和该文章中的一些示例代码,页面可能看起来像这样。

cshtml 文件可能如下所示:

@page
@using RazorPagesIntro.Pages
@model IndexModel2

<h2>Separate page model</h2>
<p>
    <input type="submit" value="@Model.Label" class="btn btn-primary"/>
</p>

cshtml.cs 页面模型:

using Microsoft.AspNetCore.Mvc.RazorPages;
using System;

namespace RazorPagesIntro.Pages
{
    public class IndexModel2 : PageModel
    {
        [BindProperty]
        public string Label { get; set; }

        public void OnGet()
        {
            if (id == Guid.Empty) {
                Label = "Create"; 
            } else {
                Label = "Update";
            }
        }
    }
}