I want to know if I can call a method in the controller when a button is clicked.
I have a view called home
and when the view is loaded, it invokes the Index
action method in the controller. I have a Button
(HTML or ASP.NET) called LoadData
. When I click the button, I need to load some data in the same view called Home
.
How do I do that?
You Define two action one for show the empty view and one for populating the view with a list :
and :
and in your view Empty.aspx
Empty
hope this helps
You've to write your Controller as follows.
And call the desired action as follows.
To do this using a simple post, you just need to post to the URL at which the controller method exists.
For example, following the standard routes setup in your global.asax "{controller}/{action}/{id}"
If you have a controller method inside your HomeController class called "LoadData" then you'd access it at the URL:
/Home/LoadData
This is the URL you'd enter into your forms
action
attribute.You can also hit this URL using an AJAX request in order to load data into the same page you're on without any postback.
Using jQuery you could do something like:
With buttons, it has to involve JQuery or JavaScript to make a call to get the data from the server, if you want to do it in AJAX form. But in its simplest form, doing:
Will invoke your action method and invoke a postback. There is an AJAX option in the System.Web.Mvc.Ajax to use an AjaxForm with AJAX options for doing the postback async, and it's easy to setup. I tend to use JQuery instead personally.
HTH.