3

I want to build custom controls in ASP.NET MVC 3. I want to create a button to which I can pass different parameters such as CSS class name and so on. However I want to be able to track events on it such as onClick or onHover...

How can I do it? Please I'm stuck with this.

Thanks.

2 Answers 2

2

Server side controls and events no longer exist in ASP.NET MVC. If you want to track events such as oncilck and onhover you could use javascript. Also you could use HTML helpers. Simply forget about the System.Web.UI namespace in an ASP.NET MVC application.

Sign up to request clarification or add additional context in comments.

Comments

1

You can create a HtmlHelper like:

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));
    }
}

In the view:

@Html.Button("CustomButton", "http://localhost")

The JS using JQuery:

$(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
    });
});

As Darin said, there are no more user controls as we had in asp.net webforms, and according to me that's a very good thing.

So the code above is a way to build a "user control".

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.