get the value of Global variable in javascript
example
var a="priti"
so want to access "a" in code behind as it's global varible
What you call code behind executes on the server and it cannot access javascript variables. One way would be to pass the value of this variable in a HTML form so that it is included the next time you submit it or send it via AJAX. Depending on what you are trying to do there might be other possibilities.
Since javascript is executed on client side to use the values in javascript you need to send it to server side, you can do so using Page Methods.
Related
As we know, ASP.NET WebForms will generate a Unique ID (as well as name) to a control to prevent collisions in the control heirarchy. Let's say we have a TextBox control with an assigned ID of "MyTextBox" in the markup. If this textbox is on a page with a Master Page then the TextBox control will be given a Unique ID of "ctl00$MainContent$MyTextBox" or something similar.
What I want to know is, for a given page, is it possible to know what the prefix WILL BE? In my above example I would like to know all controls I create on that page will be assigned with a prefix of "ctl00$MainContent$". I have examined the Page object and I cannot find an easy way to extract this information. Note: inspecting already existing controls on the page (like the TextBox) isn't an option. I simply need to know, at run time, what the prefix would be.
-- EDIT: Why do I need to do this? --
Ultimately I am trying to solve the problem that this post illustrates:
ASP.NET 4.5 TryUpdateModel not picking Form values in WebForm using Master-Page
I'm using the ModelBinding features introduced in ASP.NET 4.5. Problem is, as the above post points out, is that the name value collection found in the form will NOT match up with your model's properties. The built-in FormValueProvider expects a one-to-one match with the form key (name) and the model's properties. Unfortuantely, the form's keys will have the typical "ctl00$MainContent$" prefix to the names.
I have a semi-working solution where I created a custom IValueProvider that compares the end of the form key with the model's property. This works 95% of the time, but there's always a chance of multiple hits.
Ideally, and this is what I'm trying to figure out, if I could determine WHAT the prefix is I can then prefix that the IValueProvider's passed in key, look for that in the form and find the exact match.
So that is why I'm wondering if there's any way to know what the prefix should be for a given page.
The real answer is to simply code in such a way that you never have to know this information. that might not always be easy - but that's quite much what we do. You can certainly in code behind get/grab the "id" of the given button.
so for example, I become VERY tired of having to wire up a little toast message all over the place. So, I put in a little js routine (in the master page).
But I did need the client ID of a given control.
Well, the code behind needed (wants) to place the toast message next to whatever I clicked on.
So my server side "toast" message caller of course will after the server side code is done does the common "script" inject that will run when the page finally makes it final trip back down to the browser, displays the page, and then of course runs that script I injected.
So, my server side code does this:
MyToast2(Me, btnUpdate.ClientID.ToString, "Update ok!", "Settings changed")
So note how I get/grab/pass the "ID" of the control that the server is going to render. You can use ClientID to get the the final "ID" used for that control in code behind.
So, that btnUpdate is just a simple button placed on the web form. But who cares what super ugly "ID" the server assigns. i just need the "id" of the control so the JavaScript client side can pick up that control - and thus know/get/have the position of the control, and thus I get this result:
Or if I am some place else - again I can call that js routine - and that routine needs the current control. so might have this:
So, I can now just call a routine and pop up a message - not have to write any new js code for the gallzion notices and little pops I have all over the place.
so the little javaScript routine of course does this:
function toastcallm(cntrol, h, t, d) {
var cmd = $('#' + cntrol);
var mypos = cmd.position();
bla bla bla
But only important was that I get/determine and pass the used server "client" id to that routine - I don't really care what it is , or how to see, or how to list them out. I suppose a better jQuery selector or using wild card might work - but I really don't want to know the control ahead of time - but only that I can get the clientID used when I need it.
I simply write code that assumes somewhere along the way when I need such a client id, I simply get it and use it.
So, on the server side? Well, we always build and write code based on the control ID, but you want to get your hands on the actual id? Then you can use in the server code behind:
btnUpdate.ClientID.ToString
(ie: somecontrol.ClientID).
I have this neat function defined in a .aspx.vb file, it requires the Session variable from the context to run. I guess I could just clone the function to the other .aspx.vb file where i need it too but is there like a higher place I can put it where it would be available to both page classes and I could still have the current session variables?
You can get the session from anywhere in your application without having to pass it or anything. Just fully qualify the session method.
HttpContext.Current.Session("MySessionVariable") = Something
I have 2 simple aspx pages. On my default page, I have a simple label that's using ko.data-binding to a Session variable.
I thought if I change that variable KnockoutJS would update the user interface. When I click the button on sessionchanger page I changed the session variable that is being observed by ko. Where did I go wrong?
You have to change value of status property of viewModel instance to reflect changes on ui.
var vm = new viwModel;
ko.applyBindings(vm);
vm.status('new value');
You bind vm object to body not session object. You just use session object to initialize vm.status property.
So, you can't set new value in vm.status from the other page.
To be able to track it you should use client-server communication. It can be AJAX with polling functionality or WebSocket. So, you should check or listen server side and if any changes occur you can update vm.status property and after that it will reflect ui as you expect.
You cannot do it because asp.net rendering engine simply pass value of Session["target"] and not any link to that variable, also your knockout code isn't well written, see #Viktor Kukurba answer to get clearer idea of how to use and apply data-binding.
To achieve desired result you could use one of techniques listed below:
Preferable
Use WebSockets to notify your "Default" page about changing session variable by "Session Changer" page.
Take a look on tutorialBuilding real-time web apps with WebSockets using IIS, ASP.NET and WCF to get practical knowledge of how apply that techniques.
Workaround
As workaround you could get quite similar to required behaviour after applying next steps:
Create asp.net http request handler which would return value of Session["target"] in json format.
Create javascript function (let's call it refreshSessionTarger), which would send AJAX request to newly created asp.net http handler and update value of observable variable ( so knockout would reflect to that change, but note that you have to add ko data-binding properly).
Put refreshSessionTarger function created in step 2 into setInterval function as callback and set interval of how often in milliseconds refreshSessionTarger shall be executed.
function refreshSessionTarger(){
// perform ajax request and update variable which holds session target
};
var delay = 5000;
setInterval(refreshSessionTarger, delay)
In Page_Load() function, I have populated an arraylist and a hashtable. I need to read their values in the $(document).ready(function(){...}.
I am a beginner in terms of ASP.NET and jQuery. Please suggest a way to do it.
cheers
you can use PageMethods to make a call to your aspx page from JS. Here is a nice article on how to use page method with jQuery. You can return your "whatever" in your page method. If you want to serialize your server side objects before passing them to the client side, you can serialize them to JSON . Here is an example. You would just read your json data after your ajax call is successful("success: function(msg){//do something}") and update your HTML accordingly
you can use Page.ClientScript property to register arrays, scripts etc.
For more information view MSDN
you can create a page.method in server side and call it in the client side script that return an array of values
by adding
<scriptManager EnablePageMethods="true">
in the server side you create a function that return an array of values
ex: GetArrayResult()
if you intersting in this i will give you the rest of example
JSON.Net will help you serialize the hashtable and array to JSON, and you can store these in a hidden field. Then on the client side you can deserialize the strings to your javascript variables with:
var array = JSON.parse($('#hiddenTextField').val());
I created an asp.net Server control that derives from a LinkButton, and renders a small javascript function to the page.
I want to use this control many times on the page, but just want the javascript to be rendered once on the page. On the other hand, I rather not manually add it in a js file, because i don't want to have a chance of forgetting to add the js file in the future.
What will be the best way to go about doing this ?
Preventing duplication in client scripts
Use a registration method such as Page.ClientScript.RegisterClientScriptBlock(..). There are a couple of overloads but they all work in a similar fashion. It's smart enough to render the script only once no matter from how many control instances it's issued.
Microsoft remarks in the MSDN documentation:
A client script is uniquely identified
by its key and its type. Scripts with
the same key and type are considered
duplicates. Only one script with a
given type and key pair can be
registered with the page. Attempting
to register a script that is already
registered does not create a duplicate
of the script.
The MSDN docs also contain sample code such as this:
// Check to see if the client script is already registered.
if (!cs.IsClientScriptBlockRegistered(cstype, csname2))
{
StringBuilder cstext2 = new StringBuilder();
cstext2.Append("<script type=text/javascript> function DoClick() {");
cstext2.Append("Form1.Message.value='Text from client script.'} </");
cstext2.Append("script>");
cs.RegisterClientScriptBlock(cstype, csname2, cstext2.ToString(), false);
}
Other similar registration methods
Different methods can be used to register your client script in different ways - see each of the ClientScriptManager.RegisterClientScript*(..) methods in MSDN for more detail about each. They're all built to prevent duplication in the rendered page.
This gives you the freedom to output scripts at the control level without worrying or having to track or count scripts.
Edit:
The ClientScriptManager instance is accessed through the Page.ClientScript property.
You can use the Page.RegisterClientScriptBlock method.
Here is an example from the MSDN:
if (!this.IsClientScriptBlockRegistered("clientScript"))
{
// Form the script that is to be registered at client side.
String scriptString = "<script language=\"JavaScript\"> function DoClick() {";
scriptString += "myForm.show.value='Welcome to Microsoft .NET'}<";
scriptString += "/";
scriptString += "script>";
this.RegisterClientScriptBlock("clientScript", scriptString);
}
HTH
Any way to reference a script on a CDN and not have it duplicated multiple times? Or can I just not worry about it since it's just a pointer anyway and the browser is (?) smart enough not to load the same library twice?
In other words, suppose I want the following code inserted from a server control:
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
If I use a RegisterClientScriptBlock I can use the IsClientScriptBlockRegistered method to not have the server control load it multiple times. But, the preceding code is likely to have been put on the page anyway by either another (different) server control or by the developer who wants to use jQuery for something outside of the server control.
How do I get the server control to not load the script if the developer already loaded it?