Reputation: 13487
I want to create a HTML Helper For a button and I want to inject some javascript(jQuery) code with that button to my page. How I can do this?
Thanks
Upvotes: 4
Views: 10476
Reputation: 11
Add the below line in your view page
@Html.Button("Click Me!", htmlAttributes:new {Onclick="OnClickfunction"})
then add the following in your script section
<script type="text/javascript">
function OnClickfunction()
{
//Write Your Code here while click.....
}
</script>
Upvotes: -1
Reputation: 1715
Suggestion is to set Id of button using Id in input tag and add JQuery/Javascript code in @scripts section. This can be done with html or using helper like this
<input id="btnClick" type="button" value="Click Me!">
or using 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);
}
}
In View file (in case extension is used)
@Html.Button(ButtonType.button, "Click Me!", "btnClick")
Then add script as below:
@section Scripts {
@Scripts.Render("~Scripts/buttonScript.js")
}
or add inline JS within section or refer bundled JS. In this way, JS logic can be separated from html tag, would help in getting intellisense support and easy to maintain/test code. Within Script button reference can be retrieved using
var myButton = $("#btnClick");
Then this reference can be used for desired script logic.
Also, ensure the script section is added in _layout.cshtml as below:
@RenderSection("scripts", required: false)
Upvotes: 2
Reputation: 7618
Why don't you add a script in your htmlHelper? (of course you can add the scripts as parameters)
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());
}
}
and in your view
@Html.MyButton("Click Me")
Upvotes: 6