如何在ASP.NET MVC 3中使用System.Web.UI.WebControls.Button

3
我想在ASP.NET MVC 3中构建自定义控件。我想创建一个按钮,可以传递不同的参数,如CSS类名称等。但是,我希望能够跟踪其上的事件,例如onClick或onHover...
我该怎么做?请帮帮我。
谢谢。
2个回答

2

在ASP.NET MVC中,服务器端控件和事件已不存在。如果您想跟踪像onclickonhover之类的事件,可以使用JavaScript。此外,您还可以使用HTML助手。在ASP.NET MVC应用程序中,请忘记System.Web.UI命名空间。


1
你可以创建一个类似这样的HtmlHelper:
public static class Helpers {
    public static MvcHtmlString Button(this HtmlHelper html, string id, string url) {
        var builder = new TagBuilder("a");

        builder.MergeAttribute("href", url);
        builder.MergeAttribute("id", id);
        builder.AddCssClass("custom-button");

        return MvcHtmlString.Create(builder.ToString(TagRenderMode.Normal));
    }
}

在视图中:
@Html.Button("CustomButton", "http://localhost")

使用 JQuery 的 JS:

$(function() {
    $(".custom-button").click(function() {
        // This will handle all the click events of the buttons
    });

    $("#CustomButton").click(function() {
        // This will handle the click event on the specific button
    });
});

正如Darin所说,我们在asp.net webforms中不再有用户控件了,而在我看来,这是一件非常好的事情。

因此,上面的代码是构建“用户控件”的一种方式。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接