简体   繁体   中英

How to call a static method from a button click asp.net

I have a method that follows:

public static void UpdateAll()
    {
       // Updates database
    }

and I have a MVC Application, the view is as follows (removed lines for clarity):

<button id ="btn">Update</button>
//...
<script>
    $('#btn').click(function () {
        @{
           project.models.settings.UpdateAll();
         }
    });
</script>

The project.models.settings.UpdateAll() method fires as soon as the page loads. Is there a way of making this method load, only once the user has clicked the button?

To test I did replace the method with a simple console.log and that worked as intended.

Any pointers, examples are much appreciated.

Kind regards

I think you're missing a fundamental understanding of how web applications work.

When you put the following into your view you are declaring a chunk of server-side code that will be executed while the view is being processed on the server-side.

@{
    project.models.settings.UpdateAll();
}

The reason that it works when you replace it with a console.log is that console.log is client-side code and it executes on the client (ie in the browser).

The only way you are going to call server-side code (your UpdateAll method) from client-side code (your button click event handler) is by making an AJAX call.

The simplest thing would be to first expose your UpdateAll method as a controller action. Generally for actions that respond to AJAX calls I like to create a separate controller but that's not absolutely necessary.

public ServiceController : Controller
{
    public ActionResult UpdateAll()
    {
    }
}

Now from your client-side code make an AJAX call to that action.

the way you are doing will not work.

the method will be called when view loads as it is server side code and it will be executed on view rendering time.

so call an action using ajax and in that action call this method:

$('#btn').click(function () {
         $.ajax({
                  type: "GET",
                  url: '@Url.Action("MyAction","My")',
                  success: function(data) {

                   },
                   error: function(result) {
                    alert("Error");
                    }
         });
    });

write an action in controller:

public void MyAction()
{
project.models.settings.UpdateAll();
}

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