简体   繁体   中英

How do I set a click event in C#?

I am new to C# (my job is making me convert from JavaScript) and for some reason I cannot find a straightforward example of setting up a button that calls a method.

I am using C# ASP.NET MVC 2 with the ASPX view engine. This is not ASP.NET Web Forms .

My Index.aspx looks like:

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
    Blogs
</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

    <h2>Blogs</h2>
    <button ID="btnBlog" onclick="blogging" runat="server">Blog</button>

</asp:Content>

and I have tried several ways of doing this; this last one being:

public event EventHandler blogging()
{
    System.Diagnostics.Debug.Write("clicked");

}

Edit: Ok so doing the button like: <asp:Button ID="btnBlog" OnClick="blogging" runat="server" />

and method:

protected void blogging(object sender, EventArgs e)
{
    System.Diagnostics.Debug.Write("clicked");

}

Tells me that blogging is undefined... how do I call blogging() ?

If you meaning to call an action method from View then you might try to use one of the following examples below. When creating a link to a controller action in ASP.NET MVC , using the generic ActionLink method is preferable, because it allows for strongly typed links that are refactoring friendly.

Default: ActionLink:

@Html.ActionLink("Delete", "Delete", new { id = item.ID }) 


However, what if we want to have an image that links to an action? You might think that you could combine the ActionLink and Image and Button helpers like this:

Using Button:

<button onclick="location.href='@Url.Action("Index", "Users")';
    return false;">Cancel</button>

(with parameters)

<button onclick="location.href='@Url.Action("Detail", "Admin",
    new { Model.ProductID })';return false;">Detail</button>

or

<input type="button" title="Delete" value="Delete" 
    onclick="location.href='@Url.Action("Delete", "movies", new { id = item.ID })'" />


Using Image:

<a href="@Url.Action("Delete", "movies", new { id = item.ID })" title="Edit">
    <img src="../../Content/Images/Delete.png" />
</a>

Hope this helps...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM