我想在ASP.NET MVC 3中构建自定义控件。我想创建一个按钮,可以传递不同的参数,如CSS类名称等。但是,我希望能够跟踪其上的事件,例如onClick或onHover...
我该怎么做?请帮帮我。
谢谢。
我该怎么做?请帮帮我。
谢谢。
在ASP.NET MVC中,服务器端控件和事件已不存在。如果您想跟踪像onclick
和onhover
之类的事件,可以使用JavaScript。此外,您还可以使用HTML助手。在ASP.NET MVC应用程序中,请忘记System.Web.UI
命名空间。
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中不再有用户控件了,而在我看来,这是一件非常好的事情。
因此,上面的代码是构建“用户控件”的一种方式。