在 MVC HTML Helper 中注入 Javascript 代码以及 HTML

Inject Javascript Code along With HTML in MVC HTML Helper

我想为按钮创建一个 HTML 助手,我想用该按钮向我的页面注入一些 javascript(jQuery) 代码。我该怎么做?

谢谢

为什么不在 htmlHelper 中添加脚本? (当然你可以将脚本作为参数添加)

public static class MyHtmlHelper
{
    public static MvcHtmlString MyButton(this HtmlHelper helper,string text)
    {
        string script = @"<script> function MyMethod(){ alert('You clicked the button') ;} </script> ";
        StringBuilder html = new StringBuilder();
        html.AppendLine(script);
        html.AppendLine("<input type = 'submit' value = '"+ text + "' onclick='MyMethod()'");
        html.Append("/>");
        return new MvcHtmlString(html.ToString());
    }
}

在你看来

@Html.MyButton("Click Me")

建议使用输入标签中的Id设置按钮的Id,并在@scripts部分添加JQuery/Javascript代码。这可以通过 html 或像这样

这样的助手来完成
 <input id="btnClick" type="button" value="Click Me!">

或使用 HtmlHelper:

 public enum ButtonType { button = 0, submit = 1, reset = 2 }

 public static class HtmlHelperExtensions
 {
    public static MvcHtmlString Button(this HtmlHelper helper, ButtonType type, string textValue, string id)
    {
               string buttonTagText = $"<input type=\"{type.ToString()}\" value=\"{textValue}\" id = \"{id}\" />";
               return MvcHtmlString.Create(buttonTagText);
    }
 }

在查看文件中(如果使用扩展名)

 @Html.Button(ButtonType.button, "Click Me!", "btnClick")

然后添加脚本如下:

@section Scripts {
   @Scripts.Render("~Scripts/buttonScript.js")
}

或在部分内添加内联 JS 或参考捆绑的 JS。通过这种方式,JS 逻辑可以从 html 标签中分离出来,有助于获得智能感知支持和易于 maintain/test 代码。 可以使用

检索脚本按钮参考
var myButton = $("#btnClick"); 

然后此引用可用于所需的脚本逻辑。

此外,确保脚本部分已添加到 _layout.cshtml 中,如下所示:

 @RenderSection("scripts", required: false)

在您的查看页面中添加以下行

 @Html.Button("Click Me!", htmlAttributes:new {Onclick="OnClickfunction"})

然后在您的脚本部分添加以下内容

 <script type="text/javascript">
   function OnClickfunction()
   {
   //Write Your Code here while click.....
   }
   </script>