Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>It might help you to read up a little to read up on the differences between server-side and client-side code; they're not exactly interchangeable, and you might run into some logic issues if you assume you can call back and forth at will. Your C# code sample shows that you're trying to get confirmation from the user in the middle of a controller method - this is NOT how controller methods should work. If you want this, you should probably consider:</p> <ul> <li>Using client-side validation (jQuery has a validation plugin)</li> <li>Using AJAX requests to validate before POSTing, rather than doing it afterwards</li> <li>Splitting this action into two</li> </ul> <p>Having said that, there are places where you'd want to pass control from one to the other, so here's how:</p> <p><strong>To call server-side code (eg. controller methods) from the client:</strong></p> <p>In a word, AJAX. You can use jQuery's AJAX support or ASP.NET MVC's <code>Ajax.Action</code> and other AJAX helpers. However you do it, you basically need to POST the data to a URL that is routed to your controller method. By default, that'll be <code>www.example.com/{controller}/{method}/{param}</code> where the <code>param</code> is optional. Name the attributes of your POST request's JSON data payload the same as the parameters that your controller method is expecting. Get that method to return a JSON object (there's a built-in <code>Json()</code>) conversion) and that JSON object is what will be passed into the AJAX success handler.</p> <p><strong>To call client-side code from the server:</strong></p> <p>Not strictly possible; you can't really call directly but there are ways to trigger code on the client:</p> <ul> <li>The simplest is to put your code in the <code>$(document).ready()</code> and it'll run when the page is loaded.</li> <li>To run code at a time other than page load, have the client periodically check with the server (via AJAX) whether or not it should run some code. When you want to "call" the client-side code, have the server reply with something that means "yes", and then when the client gets that response, it runs the code. The problem with this method is that it requires the page to keep sending requests, which eats bandwidth and processing power and is generally a bad idea for big stuff, although you'll see it used a fair bit for requests that involve a very small amount of data and/or are fairly infrequent.</li> </ul>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload