I would like to get idea about, what is the fastest and secure way to make CRUD operations (Update-Edit-insert) in samepage with Ajax in WebMatrix Razor Syntax. Is it possible to do this CRUD Operations in same razor page with ajax without GET-POST webservice or other razor page?
I tried using jquery ajax to Post-Get data from other Razor pages with Output type Json and also using WCF Webservice. But they didnt really satisfy me, because in all i need another page to serve my data.
Yes, you can do this. Each separate CRUD operation would have to be wrapped in its own conditional block. The condition can test to see if a particular name/value pair has been sent to the server via AJAX (e.g. action=delete
or action=update
). When returning values back to AJAX call, make sure that the ContentType
of the Response is set correctly.
Here's a working example -
@{
if(IsAjax){
switch(Request["action"]){
case "create" :
Response.Write("You are trying to create something");
Response.End();
break;
case "read" :
Response.Write("What would you like to read?");
Response.End();
break;
case "update" :
Response.Write("Something is being updated");
Response.End();
break;
case "delete" :
Response.Write("This is a delete");
Response.End();
break;
}
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title></title>
<script src="~/Scripts/jquery-1.8.3.min.js" type="text/javascript"></script>
<script>
$(function () {
$('.crud').click(function () {
$.get('/SinglePage/?action=' + $(this).attr('id'), function (message) {
alert(message);
})
})
})
</script>
</head>
<body>
<button id="create" class="crud">Create</button>
<button id="read" class="crud">Read</button>
<button id="update" class="crud">Update</button>
<button id="delete" class="crud">Delete</button>
</body>
</html>
If anything, this illustrates how bad this approach might be in terms of maintenance etc. I would always use separate cshtml files for each data operation myself,