使用HTML onclick按钮调用C#函数

时间:2019-06-25 05:15:09

标签: c# html razor-pages buttonclick

我正在使用asp.net(C#)。我创建了一个剃须刀页面,并希望使用html按钮单击在C#中调用一个函数。该函数执行类似于稳定婚姻问题的匹配算法。例如,当管理员单击按钮“ Button1”时,必须调用C#中的match()函数,该函数应在函数中执行语句并最后返回匹配列表。我在表格中看到了一些通用的答案,但我需要更具体的内容。预先感谢

如前所述,这是一种匹配算法-以单面偏好执行双面匹配。 我已经尝试了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工作表这样的列表,可以根据需要进行编辑/删除。

编辑: 如果有人对枚举和/或布尔值有想法,我将不胜感激

4 个答案:

答案 0 :(得分:0)

无论您要做什么,都可以使用ajax来完成,因为简单的button_Click不能与razor和MVC一起使用。因此请进行ajax调用,在此之上,我建议您使用Ajax.BeginForm,这要容易得多。 / p>

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

看一下他的文章。Ajax beginform基本上允许您在ajax响应返回时访问成功方法,因此您可以在OnSuccess方法中访问从那里的控制器返回的结果。

答案 1 :(得分:0)

您可以调用一种方法来检查角色并重定向另一种操作,也可以只调用私有方法。

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](只是为了获得更好的可读性代码而已)

答案 2 :(得分:0)

尝试一下:

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

答案 3 :(得分:0)

有很多方法可以做到这一点,因为您曾经提到过剃刀页面,所以我建议您仔细阅读guide

只需使用像这样的剃刀语法

.env
相关问题