Razor page javascript execute c# only once - javascript

I'm trying to use a javascript loop to update data from my c# code. But it only execute the c# method once.
I made a test class :
public class testClass
{
public static int result;
public static int nb1;
public static int add()
{
result = result + 1;
return result;
}
}
And in my javascript I made this :
<script>
setInterval(Testing,3000);
nb1 = 0;
function Testing() {
nb1 = nb1 + 1; //this is to test that the function really restart after 3 seconds
document.getElementById('label').innerHTML = nb1 + " | " + #testClass.add(); ; // calling my c# method and print into a html label
}
And it display this on the page :
this is what is displayed on my html page
As you can see the number that show if the javascript function is restarting after 3 seconds works, but the c# method is not updating.
Do you have any solutions ?

It seems like you don't really have an understanding how HTML, JS and C# work in unison.
When a request is made to your server, It will perform calculations to return a document. This document is presented in HTML, with added logic in the form of JS to compliment it.
When using Razor, you can effectively use C# to help building the document, but not at runtime. If you want your front end document to be able to interact with the backend C# code, you are bound to using sockets(for example SignalR), or AJAX(which would be the most prominent way of asynchronous communication between a web page and a back end).
I will help you understand by stepping through the code with you..
Your razor page will start building. at one point it will detect the following line:
document.getElementById('label').innerHTML = nb1 + " | " + #testClass.add(); ; // calling my c# method and print into a html label
this is where it will call on the C# method, convert it to a value, and put the value in the JS code, so when the document gets sent to the client (your webbrowser) the code will look as follows:
document.getElementById('label').innerHTML = nb1 + " | " + {THE CALCULATED VALUE} ; // calling my c# method and print into a html label
I will refer you to this answer. Where it is explained how to do what you are trying to do.

Related

Call a Javascript function from a vb.net class

My web application which has 2 tiers. UI tier where the pages and javascript files reside. Business Layer tier with all the .net classes to save the data. In my Javascript file, i have a long function which takes an Object as a parameter and converts it onto a xml string. something like this:
function objToXML(obj) {
var strXML = '<Data>';
strXML = strXML + '<Name>' + obj.Name + '</Name>'
strXML = strXML + '</Data>'
return strXML;
}
In my business layer class, i need the same feature of converting the .net class to xml. But i do not want to write the long method in vb.net again as it has 100+ properties (above was just a sample).
is there any way by which i can use the same Jaavscript function on the server side business layer, where i do not have any acccess to the page.
Thanks.

Javascript Variable to C#

I have a question about getting Javascript Variables from a local PC JS File to a Local C# Program.
I'm writing a C# Program for the PC which needs some Variables from a Webpage which is locally located on my PC with just HTML CSS and JS which is displayed in a webview function in my C# Form.
Now I'm reading a Value from the User in my "Webpage" and want to pass this variables to my C# Code so I can use this variables further.
There are at least two ways to get any variable from a browser to your backend. One is to Post a form that contains the variable. The other is to make an AJAX call to send the variable data to some backend service. The AJAX call would, in most cases, be the way to go since no screen refresh is done and involves no interaction or initiation from the user.
use below code :
HTML and Javascript :
<head runat="server">
<title></title>
<script type="text/javascript">
function HandleIT() {
var name = document.getElementById('<%=txtname.ClientID %>').value;
var address = document.getElementById('<%=txtaddress.ClientID %>').value;
PageMethods.ProcessIT(name, address, onSucess, onError);
function onSucess(result) {
alert(result);
}
function onError(result) {
alert('Something wrong.');
}
}
</script>
Code Behind :
[WebMethod]
public static string ProcessIT(string name, string address)
{
string result = "Welcome Mr. " + name + ". Your address is '" + address + "'.";
return result;
}
More information :
C# functions returns a value and show in webpage

how to pass javascript variable to embedded Server Side code ASP.NET WebForm

let say i have a function like below in BAL.cs file
public static void xyz(string name)
{
Response.Write("Hello "+name);
}
Let say i have a javascript variable x.
now i want to call the function from BAL.aspx file
<script>
var x= "Tahmid";
<%=BAL.xyz()%> // want to pass x as a parameter
</script>
this is in webform.
It seems like there is some sort of confussion here that I would like to help solve. Server code and client code are separated. When client code executes (such as javascript) the server has no way to know what happened so your server side code (code behind) is not aware of any changes. In order to have the javascript variable information on the code behind you'll need to send that variable value back to the server and one of the mechanisms is the one provided by user2952502. I think in your case a postBack (using a submit or link button) would be more appropiate, right? I think you're trying to redraw the page based on something that the user did (since you're using javascript).
I think we should have some more information to understand the whole scope of your question and probably suggest you a better way to deal with it.
so you want to use windowfunctioname ?
since javascript is clientside and asp is serverside you could create a list of calls with parameters.
<script type="text/javascript">
var calls = [{exec: 'functionname', param : {name: 'Tahmid'}}];
document.addEventListener('DOMContentLoaded', function () {
c = calls.length;
for (var i = 0; i < c; i++) {
call = calls[i];
window[call.exec](call.param);
}
});
</script>
I hope that was an answer that helps.
The question is not clear enough .
what are u trying to do ?
just to print a dynamic text u can do with javascript function..
if u have to use a server function please specify the platform u use : MVC / WebForms..
in MVC you can use jQuery Post:
<script>
var x = "value";
$.post('#Url.Action("Action","Controller")',{name : x});
</script>

window.open() call not hitting controller first time

Please help me with this ridiculous problem.
I am passing a URL from my js form by using window.open() function that will hit a controller method and also some path variable is included..
that is,
myUrl = "controller/"+pathVar1+"/"+pathVar2+"/controllerMethod?AUTH_TOKEN=" + getAuthTokenId() +"&";
window.open(myUrl,true);
getAuthTokenId() is written in my "global.js" file And in the controller I have written the method as
#Controller
#RequestMapping("/controller")
public class ControllerName{
#RequestMapping(value = "/{pathVar1}/{pathVar2}/controllerMethod", method = RequestMethod.GET)
public #ResponseBody void ControllerMethodDefinition(HttpServletRequest request, HttpServletResponse response, #PathVariable("pathVar1") String pathVar1,#PathVariable("pathVar2") String pathVar2){
/***/
}
}
Now My problem is when first time the js is executing my call from js is not hitting the controller but next time onwards the controller is hit every time.
For this problem, the best way to investigate is that:
1) Put alert('Before open ' + myUrl); and alert('After open ' + myUrl); before and after your window.open() command, to make sure it was executed.
2) System.out.println("Controller hit. Pathvar 1 = " + pathVar1 + "; Pathvar 2 = " + pathVar2); in your controller to make sure that it is really hit.
My guess is that somehow at first time your URL is not properly initialized, so that the command won't run. But whatever the reason, it should be clear after you perform 2 above tests.

How to Show the progressbar like incremental status updates for long requests

I have to send the longtime request to server in my Asp.net application, that request i called 4 services, each service take max of 1min , so i want to show prograssbar which service is completed , i searched one link Example, it is correct about my concept but that link using iframe to load another page that page write method like
protected void UpdateProgress(int PercentComplete, string Message)
{
// Write out the parent script callback.
Response.Write(String.Format(
"<script>parent.UpdateProgress({0}, '{1}');</script>",
PercentComplete, Message));
// To be sure the response isn't buffered on the server.
Response.Flush();
}
In this code to call javascript function in parent aspx page to update details , but i have in same page to handle that concept , i removed "Parent." in my code get the error object expected how to write the code in single page
With help of jQuery (http://jQuery.com) you could do the following in javascript:
function callServices() {
var serviceUrls = ["http://yourdomain/svc1", "http://yourdomain/svc2", "http://yourdomain/svc3", "http://yourdomain/svc4"];
for(i = 0; i < serviceUrls.length; i++) {
$.ajax(serviceUrls[i], function(){ updateStatus("Service " + i); });
}
}
function updateStatus(svc) {
$("#statusBar").append("<span>" + svc + " has finished.</span>");
}
Cheers!

Categories

Resources