Good practice mvc conditional button and its code

I am encoding an MVC3 application using ajax and I have a situation.

I should show na Button only if the condition is true. Well, that is easy to do.

@if (Model.AAA == ENUM.AAA) { <button>OK</button> } 

but this button will call the ajax function.

Now I doubt WHERE PLACE MY AJAX CODE?

if i do this:

 @if (Model.AAA == ENUM.AAA) { function OK(){ $.ajax({}); } <button>OK</button> } 

The ugly code sounds !!! He sees that the code "is not in the right place, and the ajax code is" safe ", I mean, the ajax code will exist only if the button exists.

but if I put my code in the chapter section, an advanced user will be able to call the ajax function.

or if you make an @if clause to enclose a script, I will duplicate code like this

 <head type="text/javascript"> @if (Model.AAA == ENUM.AAA){ function OK(){ $.ajax({}); } } </head> .... <body> .... @if (Model.AAA == ENUM.AAA) { <button onclick="OK()">OK</button> } .... </body> 

So, What is the best practice to solve this situation, the best approach?

+4
source share
3 answers

The server must monitor the call of the request and check the correct state. @Andrew Barber points this out, but it’s more than just leaving the browser open. But an advanced user can pass an ajax request to other unauthorized users, or use them maliciously

Trying to answer the question a little deeper, it may not be a simple script like this, but a file or some JS library, maybe you do not have control over the server you are accessing ajax from. In this case, you probably want to duplicate the check.

+1
source

It almost sounds like you want to use the presence / absence of a piece of Javascript code to control access to a call on your server. Do not do that.

Your server should always evaluate whether this action can be invoked by the corresponding user at the moment. What if the user leaves the page open in his browser and there is some change in the state of the application that blocks the user from calling this action ... but their browser still displays a button? Or, if a smart user decides to play with your URLs, breaking free at the source?

I would recommend just placing javascript in a common place and calling it from there, as this keeps all of your Javascript together.

+3
source

You have only one conditional expression in your markup, for example:

 @if (Model.AAA == ENUM.AAA) { <button id="OkButton">OK</button> } 

Then tweak your Javascript slightly so that you don't include Razor (this way you can extract it into an external JS file):

 <head type="text/javascript"> WireUpButton(); function WireUpButton() { var okbutton = document.getElementById("OkButton"); if (okbutton) { okbutton.onclick = OK; } } function OK(){ $.ajax({}); } </head> 
+2
source

All Articles