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)
Related
Ill try my best to explain this. In my Hub code, i have instantiated the ConnectionMapping class. It was taken from here http://www.asp.net/signalr/overview/guide-to-the-api/mapping-users-to-connections#inmemory .
This ConnectionMapping requires a unique key for its dictionary. I have a webform code-behind called default.aspx.cs. In this code behind, I will get a unique Login Username inside the Page_Load event. How do i pass this username to the Hub to add it to the ConnectionMapping?
I tried.
IHubContext hubContext = GlobalHost.ConnectionManager.GetHubContext<MyHub>();
But i dont know what im doing after doing this. Help.
The short answer is, you don't. Not with the code you have. The issue is this sequence:
Client requests page
Server-side code runs (Page_Load)
Resulting HTML/JS is sent to client
Client connects to SignalR
At this point, you would presumably add to the ConnectionMapping. The issue being of course, that any data/variables in Page_Load are no longer available, and you'd have no way of mapping the connection you just received to that page request even if they were.
Your website needs to hold on to some piece of information, perhaps that username, and pass it to the hub on connection (possibly via the query string). The data could even be stored in the page as part of the Page_Load event (in a hidden div or through some other mechanism).
Now you have both pieces of information at the same time, and can add to the mapping normally.
I plan to develop an admin tool using Spring MVC. One view would show an order update, wherein a user would enter a product code and an update status. For every record in the database that is updated, I want to show in real time the record of the order updated.
What I am unsure is how to display this in the view from controller - would i be using a jquery grid to perform this or is there some feature built in spring mvc
Read this article , but seems that may be an overkill for my simple app
If a user is filling out a form in your view (entering the product code and update status) and you want to display the data in that view after they submit (without page reload), you will need to use AJAX. Hook a JavaScript function to an event in your form:
$("#submit_button").click(function(){
$.ajax("/path/to/controller/route", {
// Insert various request options...
data: {
// data to be sent along with the reqest.
}
success: function(data){
// Define function that is fired when the AJAX request returns successfully.
}
});
});
This path should hit an endpoint on the server side that will perform the update on your desired record, and can return the info about the record that you desire back to the client side. When the request returns successfully, you can do whatever you want with the data via the success function's data argument. You can find more information about the jQuery AJAX functions here and more about jQuery Events here.
If by "in real time" you mean on a timer, instead of on some user triggered event, the solution is similar, but the AJAX request would be defined in the callback function of setTimeout() call or a similarly acting jQuery provided function (such as delay())
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.
Assume you have a page in ASP.NET where it makes sense to use JavaScript/jQuery to modify the DOM with values that will eventually be read by the server on submit. For example, you have a form that allows end users to add/remove objects (like dependents on a health insurance form or assets on a loan application).
What are some ways to ensure that these items are detected and retrieved by the server once the information is submitted?
I've tried a few things that work, but none of them seem perfect so I wanted to see what the community had to offer.
Also, I'm not looking for suggestions that avoid dynamic DOM elements (like use a Wizard, etc.). I'm specifically trying to improve my technique with dynamically created DOM elements.
There are two ways to do something like this:
First: post only the information on submit. As long as you add both a name and an id attribute to every element in your DOM, every element is represented in Request.Form, so you can easily iterate through this collection.
I tend to have a naming convention like insurance_row_1, insurance_row_2 and so forth. You can find all rows like Request.Form.AllKeys.Where(k=>k.StartsWith("insurance_row_")).
When you want to save every action on the server:
Maintain a state container in javascript, that holds information in some dictionary-like control, where you put every action that has been performed by your application, and a state whether the server has processed them. Something like:
var stateContainer = [
{ 'put-insurance-row-1', false },
{ 'delete-insurance-row-1', false }
];
Do an AJAX request to the server to perform such an action, and use the state-container's key to track whether the request succeeded or failed. Set the state to 'true' when the request has been successfully submitted. Make sure to do this in order in which you receive the events, so send them one-by-one to the server to ensure that you keep a valid state.
You can (try) to prevent closing the browser if some states aren't persisted yet.
why are you using client side code to do this? i would go the route of doing a postback and adding a control from server side code. the built in ajax updatepanel should handle this very quickly.
I am a VB.net winforms programmer attempting to build an ASP.Net app. I use data classes(objects) through reflection in most of my vb projects and was trying to adapt it to ASP.net using the VB code behind. I have a webpage that serves as an add/edit page for contact info. I instatiate my class which grabs the contact data from the data base then I have a process that loops through the controls on the form and matches up with a property in the data class. I can display data no problem. When I edit data and click the submit button my code calls a then loops through the controls on the form again and matches the control to the property of the data class to update the property of the class. However, my data class is no longer valid. I know web programming is different then winforms but I can't seem to get over the hump on this one. Is this the wrong way to go about this? Is my data class only available on the server side? Do I just reinstantiate the initial class and then loop through the propeties and change what the user changed and then call the update method (see redundant)? How can I get data class into a session object (I made an attempt in the past but was under tight deadlines and had to abandon it, maybe I need to revisit it?)?
Thanks
If you decide to keep some of your data in Session, you owe it to yourself to look at this post. Your code will be much cleaner and easier to maintain.
Yes, you need to reload the data class from the database as one option, or use an alternative approach. The reason is web is stateless, so all local variables are destroyed then the server side page unload process occurs. This means that in between requests, you need something to store your data.
You can read/write an object via the Session colleciton, as so:
Session["A"] = myobj;
myobj = (ObjType)Session["A"];
And so session stores an object for a specific user. Alternatively, cache stores application level data, so one instance of an object is available to all users (where session is unique to each user). You can make cache unique to a user by appending a user ID to the cache string.
var o = Cache.Get("A");
if (o != null) { .. }
Cache.Add("A", o, ...);
And so these mechanisms help you temporarily retain data.
You need to save your data class somewhere, usually in a session variable, otherwise it goes away as soon as the page gets sent back the user. Or else you need to recreate the data class again upon posting.