簡體   English   中英

使用 HTML onclick 按鈕調用 C# 函數

[英]Call a C# function using HTML onclick button

我正在使用 asp.net(C#)。 我創建了一個 razor 頁面,並希望使用 html 按鈕單擊在 C# 中調用一個函數。 該函數執行類似於穩定婚姻問題的匹配算法。 例如,當管理員單擊按鈕“Button1”時,必須調用 C# 中的函數 matching(),該函數應執行函數內的語句並最終返回匹配的列表。 我在表格中看到了一些通用答案,但我需要更具體的答案。 提前致謝

如前所述,這是一種匹配算法 - 執行具有一側偏好的兩側匹配。 我已經嘗試過 html“Button1_Click”解決方案。 這是非常通用的,不符合我的代碼。

這是我到目前為止所做的:

html代碼:

 <form id="form1" runat="server"> <button type="submit" id="cmdAction" text="Button1" runat="server"> Button1 </button> </form>

C#代碼:

public ActionResult OnGet()
{
if (NTUser.Role != Role.Admin)
{return RedirectToPage("/Denied");}
matching();
return RedirectToPage();
}    
public void matching()
{//body}

我在 html 端使用的按鈕是“匹配並顯示結果”

我希望輸出是一個像 Excel 表一樣的列表,如果需要,可以編輯/刪除。

編輯:如果有人知道如何使用 enum 和/或 bool 進行操作,我也將不勝感激

您可以調用一個方法來檢查角色並重定向另一個操作,或者只調用私有方法。

public ActionResult OnGet()
{
     if (NTUser.Role != Role.Admin)
     {
        return RedirectToPage("/Denied");
     }
     else
     {
        return RedirectToAction(Matching);
     }
      ...other if with return
}

public ActionResult Matching()
{
   //dosomething
}

看法

如果您需要發布然后使用它

@using (Html.BeginForm("OnGet", "YourControllerName", FormMethod.Post))
{
    <button type="submit" id="cmdAction" runat="server">
        Match and Show the result
    </button>
}

如果你需要得到

@Html.ActionLink("Match and Show the result", "OnGet", "YourControllerName") //without params

不要忘記添加屬性[HttpPost][HttpGet] (獲取代碼只是為了更好的可讀性)

無論您嘗試做什么,都可以使用 ajax 完成,因為簡單的 button_Click 將無法使用 razor 和 MVC。

https://www.c-sharpcorner.com/UploadFile/0c1bb2/ajax-beginform-in-Asp-Net-mvc-5/

看看他的文章 .Ajax beginform 基本上允許您在 ajax 響應返回時訪問成功方法,以便您可以在 OnSuccess 方法中訪問從控制器返回的結果。

嘗試這個:

<a href="@Url.Action("OnGet", "ControllerName"> Display Text</a>

有很多方法可以做到這一點,因為你提到過剃刀頁面,所以我建議你閱讀本指南

只需像這樣使用剃刀語法

@using (Html.BeginForm("ActionName", "ControllerName", FormMethod.Post)) { 
   <input type="submit" value="Match" />
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM