Yogesh
Yogesh

Reputation: 3076

Calling a specific action of a controller on the click of HTML button(Not Submit or Form's post Button) Asp.net MVC

When we click a Form's submit button, then action of the controller which is having HTTPPost attribute is called but what if i want to call or perform an action when a normal HTML button is clicked Although following articles

http://www.codeproject.com/Tips/198477/Calling-a-MVC-Controller-and-Action-Method-using-H

HTML button calling an MVC Controller and Action method

tells the approach but both of these are using controller name in view, So view has to know about controller, I am looking for an answer that view wont have to know about controller. because views has to be Independent from Controller, Views should not know about controller So, if you know the answer then please reply

Upvotes: 8

Views: 49808

Answers (3)

Darin Dimitrov
Darin Dimitrov

Reputation: 1039000

You cannot have 2 actions on the same controller with the same name and the same HTTP verb. So what you are asking doesn't make sense. You could invoke the same controller action as the one that rendered the view without specifying an action and controller name. The reason why Html.BeginForm() works without specifying an action and controller name is because the form is sending a POST request to the server and you can distinguish the 2 actions.

Upvotes: 0

Ben
Ben

Reputation: 1787

To execute an MVC action from the client side (i.e. from a view) you need to hit a URL (with any verb: get, post, put, etc). Therefore to execute an action form a view you will need to know the URL of that action, by default that URL is directly mapped to the controllername/actionname but you can re-define this if you want to create more abstraction between view and controller.

Given this your button just needs to be a link to a URL or linked to js to do an Ajax http request.

Hope that helps.

Upvotes: 0

Dave Alperovich
Dave Alperovich

Reputation: 32500

any form that directs your user to url created by

<a href='@Url.Action("{action}", "{controller}")'> click me </a> 

or

@using(BeginForm("{action}", "{controller}")

will do what you want.

That can be with a

  • form
  • button link

It's the destination that matters. The View does not "know" anything about the action or controller. The helper does.

Upvotes: 16

Related Questions