Ado Ado - 3 months ago 9
HTML Question

Call a C# method from an html a tag

I have the following C# method, how can I call it from an HTML a tag?

<a href="#" runat="server" onclick="MyFunction()">CLICK</a>
public void MyFunction()
{
Response.Write("<script>alert('Hello');</script>");
}

Answer

You can use jQuery ajax to MVC action:

function CallMyCShartAtion(id)
{
   $.ajax({
      url: 'urlToController', //path to the contoller's action
      data: { id: id }
   }).done(function() {
      alert('Added'); 
   });
}

And then

<a href="#" runat="server" onclick="CallMyCShartAtion(5)">CLICK</a>

http://api.jquery.com/jQuery.ajax/