0

I want to have a onclick event in the my code behind in the controller class of my code but how do I do this with mvc. I can't find anything on google all I've found is for button type submit but I don't want a button of type submit.

This is my button in my view:

<button type="button" id="game" onclick="">
</button>
2

2 Answers 2

1

If you are looking for an ASP.NET web forms Server side events behavior, you will have to create it yourself. You CAN do (easily) an Ajax call to a controller, get a response and do what ever you want with it. More information Here.

Small example of attaching client side (javascript) onclick event to your button, that calls a controller action on the server and show the results in the console. you need to change this line

@Html.ActionLink("Controller", "Action")

with your controller and action names.

 <script type="text/jscript">
    $('#game').click(function () {
        var url = '@Html.ActionLink("*Controller*", "*Action*")';
        $.get(url, null, function (data) {
           console.log(data);           
           /// Add javascript code here to execute when you get the answer from the controller  
        });
    })
</script>
Sign up to request clarification or add additional context in comments.

Comments

0

Onclick is a javascript event. You can't react from your mvc controller to it directly. If you need to react to anything that happens on the client, you have to do a postback, either by using a form or using ajax and doing asynchronous request...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.