I’m coding an MVC3 application with ajax and I got a situation.
I have to show na Button only if an condition is true. Ok its easy to do.
@if (Model.AAA == ENUM.AAA)
{
<button>OK</button>
}
but this button going to call an ajax function.
Now my doubt is, WHERE A PLACE MY AJAX CODE?
if I do this:
@if (Model.AAA == ENUM.AAA)
{
function OK(){
$.ajax({});
}
<button>OK</button>
}
it’s sound ugly code!!!
It’s seens that the code it’ not in the right place but the ajax code is “safe”, I mean, the ajax code will only exist if the button exist.
but if I place my code in head section, An advanced user will be able to call the ajax function.
or if a make an @if clause to enclose the 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 face this situation, the best approach?
The server should control the request call and check for the correct state. @Andrew Barber points this out, but that is not just leaving the browser open. But the advanced user could share the ajax request, with others that don’t have permission, or use it maliciously
Trying to answer the question in a bit more depth, it could be not a simple script like this, but a file or some JS library, maybe you don’t have control about the server you ajax is accessing. In that case, you’d probably want to duplicate the verification.