Calling a static method from cshtml file - javascript

I'm trying to work on a clickable DIV from some vertical tab panel. What I want is when clicking on a specific DIV call a static method to do some tasks, so I did this:
<div class="tabbable tabs-left">
<ul class="nav nav-tabs">
<li onclick="myEvent()">Tuttle</li>
then, my JavaScript code:
<script>
function clickEvet() {
alert("alert test message");
#MyProject.myMethod()
}
</script>
Calling the function "clickEvent()" works. The problem is that #MyProject.myMethod() is called no matter what, in other words, #MyProject.myMethod() is being executed as soon the page loads. I want it only when I click on my div.
This is from a cshtml file and I'm using .net 4.5
SOLUTION:
I'm editing my question to post the answer for future references...:
Thanks to other comments I finally understood how to work with Ajax and make it work. Here is the solution:
<script>
function vaxGUID() {
$.ajax({
type: 'POST',
url: "/VAXBean/bmx",
data: '{"Name":"AA"}',
contentType: 'application/json; charset=utf-8',
dataType: 'html',
success: function (data) {
bmx = "http://www.vitalbmx.com";
$('a.varURL').attr('href', bmx);
GUID = data;
alert("Good response - " + data + " - " + bmx);
},
error: function (data, success, error) {
alert("Error : " + error);
}
});
return false;
}
</script>
With this Ajax method I'm making the call to some static method in the background

I want it only when I click on my div. <= When you click on the DIV that is being done in the browser after the request has been sent. There is no way for the browser to call directly back inside a method in your application. The HTML has already been generated and sent by the server in the request to the client and that is where that communication cycle stops.
If you want a click (or any other event) to do something specifically on the server you need to do one of these standard actions that are used to communicate back to the server.
Create an AJAX request back to your MVC Controller to get data (or whatever).
Create a link (standard url)
Create a form post back
And of course the #MyProject.myMethod() executes every time your page is rendered because your razor view is a code file that is being interpreted line by line so it can be rendered and sent to the client that requested it. What would be valid here is if myMethod output some javascript or something that the browser could understand and do something with, that is what would be expected.

You can't do it. All # (Razor) expressions is resolved during page rendering on server. That's why you method is called.
Probably, you need to make an Ajax call.
Look for a more detailed explanation here:
How do I call a static method on my ASP.Net page, from Javascript?

Related

Jquery AJAX button call in Umbraco BackOffice

Hi I just created a simple new option for umbraco backoffice, it is a simple html page which displays a button to click.
Simple form
This button should send an ajax call to an UmbracoApi, but the request never reaches the webapi. Below the Api Code:
API Code
The Ajax call is a simple Jquery Ajax call in the event click of the html button.
I'll appreciate any help you can provide me, in order to complete this ajax call.
I think yor problem is the way you are calling it:
not sure if url casing not same as Controller and action will cause routing failure or not, but might as well make then the same
you action is binding a primitive type, from my understanding of webapi - primitive type will check at querystring otherwise specifically tell it to look at body
more info about this, checkout https://learn.microsoft.com/en-us/aspnet/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api
so base on above two statement, try change your call to:
$("#btnGetData").click(function() {
$.ajax("http://localhost:44302/Umbraco/Api/StripeBackOfficApi/GenerateLockBoxile?date=" + $('#txtDate').val(), {
type: "GET"
}, cache: false, success: function(data, status, headers, config) {
if (data) {
alert("Done!");
}
}, error: function(jqXHR, timeout, message) {
console.log("Error: " + message);
}
});
});

How do I reload a page without the user noticing?

I've been trying to figure out how to reload a page and pull dynamic info from a server without users noticing the page has been reloaded. For instance, if I want to create a 'live' message board system when the board updates every time other people make a comment or post a message.
I noticed that Javascript has a boolean function .reload() that when set to false reloads the page from the cache and when set to true reloads the page from the server, but from what it looks like, the function does something similar to reloading the browser. Is there another way do what I'm trying to do?
Something like this...
function getContent()
{
return new Promise(function(resolve, reject){
var url = "http://yourendpoint.ext"
$.ajax({
url: url,
success: function(data)
{
resolve(data);
},
error: function(err)
{
reject(err);
}
});
}));
}
// Usage
getContent()
.then(function(data)
{
$('#some-element').html(data);
});
Are you sure you really want to do an reload?
What you could do is make an AJAX Request to the server and display the result, without even reloading the Page. I would recommend using jQuery for this, just out of comfort.
AJAX stands for Asynchronous JavaScript and XML. In a simple way the process could be:
User displays page, a timer is started
Every 10s (or 20s or whatever) you do an AJAX Request using JavaScript, asking the server for new data. You can set a callback function that handles the result data.
Server answers with result data, your callback function inserts the new data.
Code Example (taken from jQuery Docs):
$.ajax({
method: "POST",
url: "target.php",
// Data to be sent to the server
data: { name: "John", location: "Boston" },
// success will be called if the request was successfull
success: function( result ) {
// Loop through each Element
$.each(result.newElements, function(index, value) {
// Insert the Element to your page
$('.classOfYourList').append(value);
}
});
});
Just set the proper endpoint of your server as the target and insert whatever you want to do in the success function. The function will get an answer containing whatever you sent to it from the server. More Information in the jQuery Documentation:
You can Achive what you want using AJAX. you can use ajax with either javascript or jquery. You can load the content you want dynamically without reloading the entire page. here is a quick example.
Here is a <div> with id load where your content will be loaded.
<div id="load">Loaded Content:</div>
<button id="load_more">load more</button>
JQuery to request for the data, where getdata.php is the php file which will send data you want to display.
<script type="text/javascript">
$(document).ready(function(){
$("#load_more").click(function (){
$.post("getdata.php", {variable1:yourvariable, variable2:ifneeded},function(data){
//data is the string or obj or array echoed from getdata.php file
$('#load').append(data); //putting the data into the loaded div.
}
});
});
});
</script>`
finally getdata.php file
<?php
//fetch data from Databas eif needed. or echo ut what you want to display in the div.
echo "This is a small example of using JQuery AJAX post request with PHP.";
?>
Hope that helps!

How to get data param on the destination page from Ajax response call

I am Opening dynamically a page using Ajax, to prevent browser refresh. It opens and it runs scripts on the destination page. but before executing the script, I want them to retrieve the parameters like request.querystring but in Javascript.
This is my code that opens the page.
function cargarPagina(para1) {
$.ajax({
url: "/tarea.aspx",
context: document.body,
data: { "p1": para1 },
type: 'POST',
success: function (responseText) {
$("#maincontent").html(responseText);
$("#maincontent").find("script").each(function (i) {
if ($(this).text() != "") {
$("#maincontent").find("#hola").val(para1);
//alert(para1); //eval($(this).text());
}
});
},
async: true
});
}
After that, the tarea.aspx opens and executes scripts blah blah.
But before executing scripts, I want to get the "para1" value that was sent within the ajax POST call.
Any help would be much appreciated.
You are doing a POST not to the page, but to a server. The server then looks at your POST and says "oh, it looks like this is the page that you are requesting", and serves up some html content. The javascript on that served up page does not have any knowledge of the original POST, or how it (the page) came to be created.
If you want to get the POST parameters into the destination page, you must handle the POST request on the server, and then write the parameters in to the output page, via ASP.net or PHP or whatever scripting language you are using.
Alternatively, you could use GET instead of POST, and then the parameters would be available in the URL

Ajax Call Confusion

before we start apologies for the wording and lack of understanding - I am completely new to this.
I am hoping to run a php script using Ajax - I don't need to send any data to the php script, I simply need it to run on button press, after the script is run I need to refresh the body of the page. What I have so far:
HMTL Button with on click:
<font color = "white">Next Question</font>
JS Ajax call:
function AjaxCall() {
$.ajax({
url:'increment.php',
type: 'php',
success:function(content,code)
{
alert(code);
$('body').html(content);
}
});
}
this runs the php script but doesn't stay on the current page or refresh the body - has anyone got any ideas - apologies if this is completely wrong I'm learning - slowly.
Many thanks in advance.
**As a small edit - I don't want a user to navigate away from the page during the process
How about using load instead of the typical ajax function?
function AjaxCall() {
$(body).load('increment.php');
}
Additionally, if you were to use the ajax function, php is not a valid type. The type option specifies whether you are using GET or POST to post the request.
As far as the dataType option (which is what I think you mean), The Ajax doesn't care what technology the called process is using (like ASP or PHP), it only care about the format of the returned data, so appropriate types are html, json, etc...
Read More: http://api.jquery.com/jquery.ajax/
Furthermore, if you are replacing the entire body content, why don't you just refresh the page?
your ajax should be
function AjaxCall() {
$.ajax({
url:'increment.php',
type: 'post',
success:function(data)
{
console.log(data);
$('body').html(data);
}
});
}
if you want to learn ajax then you should refer this link
and if you just want to load that page then you can use .load() method as "Dutchie432" described.
If you are going to fire a javascript event in this way there are two ways to go about it and keep it from actually trying to follow the link:
<font color = "white">Next Question</font>
Note the return false;. This stops the following of the link. The other method would be:
<font color = "white">Next Question</font>
Note how this actually modifies the href to be a javascript call.
You can study about js and ajax here http://www.w3schools.com/ajax/default.asp will help a lot. Of course all js functions if called from internal js script should be inside <script></script> and if called from external you call the js gile like <script src"somejs.js"></script> and inside js there is no need for <script> tags again. Now all those function do not work by simply declaring them. So this:
function sayHello(){
alert("Happy coding");
}
doesn't work because it is just declared and not called into action. So in jQuery that you use after we declare some functions as the sayHello above we use:
jQuery(document).ready(function($){
sayHello();
});
Doing this we say that when everything is fully loaded so our DOM has its final shape then let the games begin, make some DOM manipulations etc
Above also you don't specify the type of your call meaning POST or GET. Those verbs are the alpha and omega of http requests. Typically we use GET to bring data like in your case here and POST to send some data for storage to the server. A very common GET request is this:
$.ajax({
type : 'GET',
url : someURL,
data : mydata, //optional if you want to send sth to the server like a user's id and get only that specific user's info
success : function(data) {
console.log("Ajax rocks");
},
error: function(){
console.log("Ajax failed");
}
});
Try this;
<script type="text/javascript">
function AjaxCall() {
window.location.reload();
}
</script>
<body>
<font color = "white">Next Question</font>
</body>

ASP.NET AJAX - ScriptManagerProxy and handling html button clicks

I am trying to figure out how to accomplish the following:
Handle client-side click event of button - prevent postback if result of javascript call is false (e.g. onclick="js:return IsThisAllowed()")
Javascript method will return true or false, depending on result of call to generated web service method using ScriptManagerProxy
The code below is simplified down to the main components that I am referring to in this question. I can alert() the return value no problem, but the part I'm having trouble with is how I can return the result of the web service method call back to the button onclick handler? Since the function Finish() is called in a separate thread upon success of what I assume is the XmlHttp.send() call, how can I send the value of the response as the return value of the javascript method? Am I going about this all wrong?
I've used similar code many times before to update the DOM with the return values, such as within a <div>, but never had to worry about capturing the return value and using it within my script.
What I have so far:
.NET web service method (VB.NET):
<WebMethod()> _
<ScriptMethod()> _
Public Function IsAllowed() As Boolean
Return True
End Function
.NET code for the page to generate AJAX web service methods, and html button
<asp:ScriptManagerProxy ID="ScriptManagerProxy1" runat="server">
<Services>
<asp:ServiceReference Path="~/WebServices/MyWebService.asmx" />
</Services>
</asp:ScriptManagerProxy>
<asp:Button ID="_btn" runat="server" OnClientClick="js:return IsAllowed();" />
Javascript
<script type="text/javascript">
function IsAllowed(orderid) {
if (!processing) {
processing = true;
var ws = new MyWebService();
ws.IsAllowed(Finish, Error)
// return TRUE if call to IsAllowed returns true!!!
return false;
}
}
function Finish(result) {
alert(result)
}
function Error() {
}
</script>
You can't do this: the call to the web service is an asynchronous request to the server that immediately returns control to the client - and your javascript is (almost) always going to finish executing before the request completes (most likely before the request is even delivered).
Since you don't know when you'll receive the response from the call to ws.IsAllowed, you need to handle it in your callbacks (Finish and Error).
(This is true whatever AJAX mechanism you're using.)
I'm not familiar enough with ScriptManager-based AJAX to tell you exactly how to do this, but the general idea is that I'd turn it around: instead of canceling an ASP.NET button's click event, I'd only trigger the ASP.NET button if the AJAX call returned true.
Using jQuery, I'd do it by making the AJAX call from a vanilla HTML button (not an ASP.NET web control). In the success handler (the equivalent of Finish), I'd trigger my ASP.NET button (which I'd probably hide) when the return value is true.
Have you considered using jQuery?
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
url: "~/WebServices/IsAllowed.asmx/{Method Name}",
data: ('{ whatever data is needed for decision making json serialized }'),
success: function (msg) {
alert(msg);
},
error: function (request, status, error) {
alert(err.Message);
alert(err.StackTrace);
}
});

Categories

Resources