ICallBackEventHandler does not update controls with form values - asp.net

I want to use ICallBackEventHandler however when I use it to call back to the server I find that my form control objects don't have the latest form values. Is there a way to force populate the values with the form data?
Thanks.

Have a look at http://msdn.microsoft.com/en-us/magazine/cc163863.aspx.
In short, you have to clear the variable '__theFormPostData', and call the 'WebForm_InitCallback()' before the 'CallbackEventReference' script. This updates the form values with the user input values. Something like this:
// from the above link
string js = String.Format("javascript:{0};{1};{2}; return false;",
"__theFormPostData = ''",
"WebForm_InitCallback()",
Page.GetCallbackEventReference(this, args, "CallbackValidator_UpdateUI", "null"));

You obviously still dont have the same issue but wha you need to do is recall WebForm_InitCallback() prior to your JavaScript Callback Code. This will get the page to refresh the POST values in your Request.Form object.
When you now do a PostBack the values modified during Callbacks will be available. It goes without saying they will be available during Callbacks.
etc
function SomeCode()
{
__theFormPostCollection.length = 0;
__theFormPostData = "";
WebForm_InitCallback();
ExecuteMyCallbackMethod("yaday", "yadya");
}

Related

Update Javascript variable from code behin Thread

I want to implement a serverside download process which reports its progress to the client.
I defined a global variable in my .aspx site class:
Public progressStatus As Integer
Then a start a new Thread to download the images in a List, which also changes the value of the global variable:
For Each imageUrl In imageFiles
currentUrlCount = currentUrlCount + 1
indexOfUrlSplit = imageUrl.LastIndexOf("/")
localFilename = imageUrl.Substring(indexOfUrlSplit + 1)
If localFilename <> "" Then
httpClient.DownloadFile(url, localImage)
progressStatus = CInt((currentUrlCount / totalUrlCount) * 100)
End If
Next
I use the SetIntveral Javascript methods to check for the value of the global variable every 2 seconds:
var progStat;
setInterval(function() {
progStat = <%=progressStatus%>;
document.write(progStat + "\n");
}, 2000);
Through debugging I checked that the global Variable in the Code behind is calculated and changed correctly. Anyway, Javascript keeps the initial Value of 0.
I would be glad if someone could help me with that problem!
Thank you very much everybody,
Max
When you use syntax like that:
progStat = <%=progressStatus%>;
progressStatus value is retrieved once and converted to string when page is rendered. At that time value is 0. It isn't retrieved from server every time you call that script.
It means javascript function rendered on your page looks like:
progStat = 0;
When you keep calling that function multiple times client-side it does not change as page isn't re-rendered.
You need to make use of an Ajax call to retrieve the value from the server. Use the result from the call together with JQuery and then update the UI

Request.Form "Collection is only readonly" when trying to set text box content

Saving the values in the Lists & works fine.
abc= (ABC)(Session["xml"]);
string ctrlStr = String.Empty;
foreach (string ctl in Page.Request.Form)
{
if (ctl.Contains("something"))
{
ctrlStr = ctl.ToString();
abc.student[0].marks[j].science.something.Value = Convert.ToDecimal(Request.Form[ctrlStr]);
}
Want to retrieve the values from the saved object when I click on edit button back on the respective dynamic textboxes....
foreach (string ctl in Page.Request.Form)
{
if (ctl.Contains("studentname"))
{
ctrlStr = ctl.ToString();
(Request.Form[ctrlStr]) = abc.student[0].marks[x].science.studentname.ToString();---Gives an error stating the collection is only readonly
}
}
Request.Form — like the Request object generally — is read-only, reflecting the fact that, by the time you are responding to a request, the request itself cannot be changed. ASP.NET uses the values from the form POST to create server controls on the Page, and these allow you to control the values of the input and other form elements that are written to the Response object.
In your case, the TextBox controls are being generated dynamically, so they are not automatically bound to form values — hence your problem. You will need to keep references to the controls when they are created (or find them afterwards using the FindControl() method) and set their Text property.
(original answer follows)
The Controls collection becomes read-only at a certain point in the construction of the page. You have to do manipulation before that point. I don't remember offhand when it is, but you're safe with OnLoad through OnPreRender.
Where is your code firing from?
Update: Okay, I see what you're trying to do. This will be easiest if you're dealing with server-side controls (that is, controls generated by ASP.NET. That would look like this in your aspx (or ascx):
<asp:TextBox runat="server" ID="studentname"/>
Then you could update the value like this:
abc = (ABC)(Session["xml"]);
studentname.Text = abc.student[0].marks[j].science.something.Value.ToString();
That will set the value of the studentname text box automatically without needing to search through all of the Request.Form items. (Assuming you set j somewhere... I don't know the context for that.)
I can't tell for sure from your code, but it looks like you may just have a "plan HTML" input, which would look more like this:
<input type="text" name="studentname"/>
In that case, there is no simple way to update the value from your page's code, so I'd start by making sure that you're using server-side controls.
You can set the Request.Form values with reflection:
Request.Form.GetType().BaseType.BaseType.GetField("_readOnly", BindingFlags.NonPublic | BindingFlags.Instance)
.SetValue(Request.Form, false);
Request.Form["foo"] = "bar";
What you are trying to achieve?
The Form collection retrieves the values of form elements posted to the HTTP request body, with a form using the POST method. - http://msdn.microsoft.com/en-us/library/ms525985(v=vs.90).aspx

ASP.Net Auto-populate field based on other fields

I've just moved to web development and need to know how i can implement below requirement using asp.net and vb.net.
I have three fields in a form which are filled by users. Based on these three values, i need to auto-populate the 4th field. I have planned to implement this in the following way
Write a separate class file with a function to calculate the possible values for the 4th fields based on 1st 3 inputs. This function can return some where between 1-10 values. So I've decided to use drop-down for 4th field, and allow users to select the appropriate value.
Call the above function in onchange function of 3rd field and take and use the return values to populate the 4th field. I'm planning to get the return values in array field.(Does this need a post back?)
Please let me know how if there is better way to implement this.
Thanks.
You may want to consider doing this with Javascript. You could read and control the fields pretty easily with pure Javascript, or using a nice library like jQuery (my favorite). If you did it this way, no post-back would be required and the 4th field would update immediately. (Nice for your users)
You can also do it with ASP.NET for the most part. "onchange" in ASP.NET still requires Javascript as far as I know, it just does some of it for you. A post-back will definitely happen when you change something.
You need javascript or to set autopostback=true on your form elements.
From a user perspective the best thing is to use javascript to populate the field for display, BUT when the form is submitted use your backend function to validate it. This will make sure the user didn't change the value.
An easy way is to use jQuery for the UI (that way you don't have to worry about long winded javascript and deal with browser compatibility as it's already taken care of for you) and have it call to the server for the data. For the server, your easiest route is to return JSON for looping values.
Include your jQuery:
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>
Then add in a handle for the JavaScript:
<script type="text/javascript">
function autoPopulate() {
var value1 = $('#ddl1').val();
var value2 = $('#ddl2').val();
var value3 = $('#ddl3').val();
var url = 'path/to/your/file.aspx?value1=' + value1 + '&value2=' + value2 + '&value3=' + value3;
$.getJSON(url, function(data) {
data == null ? return false : data = eval(data);
var ddl = $('#ddl4')[0];
for (i = 0; i < data.length; i++) {
var option = new Option(data[i][0], data[i][1]);
if ($.browser.msie) {
ddl.add(option);
} else {
ddl.add(option, null);
}
}
}
}
</script>
(Yes, I know I used a native loop but I'm little lazy here today :) )
Now, for your server side code you'll want your code your page to return data in the format of:
[['value1','text1'],['value2','text2'],['value3','value3']]
so something like:
<script type="vb" runat="server">
Private Sub Page_Init()
// get your data
// loop through it and add in values
// ex.
Dim result As String = "[" //start multi-dimensional array
For Each Item As String In data
result += String.Format("['{0}','{1}'],", _value, _text)
Next
result = result.SubString(0, result.Length - 1) // removes trailing comma
result += "]" // closes off m-array
Response.Write(result)
Response.Flush()
End Sub
</script>

Gridview manipulation using JQuery and JavaScript

I have an ASP.NET gridview I want to manipulate using JavaScript/JQuery. The problem I THINK I'm going to have with my approach is that the server won't have any knowledge of the rows that I am appending via gridview since the html representation of the gridview control is coupled with the object model that lives on the server. So here is what I need to do:
I need to append to the gridview when a user submits data, and submit each row in the batch of entered data to the server to be processed. Because I have other ASP.NET controls that will contain data that I want to submit, I'd like to submit all that data via a traditional postback to the server.
How do I implement this approach if possible?
If not possible, could you please explain?
Thank you very much for your help.
var queryString = "";
// This could be based on a number of different events
$('#finishButton').click(function(){
// Iterate through each input (you could add other form elements)
$('#myForm input').each(function(){
// Build your query string to post to your aspx page
queryString += $(this).attr("name") + "&" + $(this).val() + ",";
});
});
// Make sure special chars are escaped
queryString = escape(queryString);
// POST the form to your aspx page
$.ajax({
type: 'POST',
url: 'myFormProcessor.aspx',
data: queryString,
// Upon a successful POST, successHandler will be called
success: successHandler
});
// Add the new data to the grid
function successHandler(){
// Clone the last row
$('#myTable tr:last').clone(true).insertAfter('#myTable tr:last');
// Here you could just break apart the query
// string you build in the above code
// and use those values to change the values
// in the row you added to the grid
}
Make sure to unescape the query string in your aspx page, and then break it up by the delimiters you're using. I used '&' to separate key/value and commas between variables (inputs).

Passing flash variables to asp.net

I don't know much about Flash but we are working on a site that has a flash form and when the users pick an option, like selecting a value from a drop down list, we need the value to be passed to asp.net server-side code. What's the easiest way to do this?
Flash can invoke server side service. So use GET or POST to pass data
You could explore these options:
1) Communicate between the SWF and the containing page through JavaScript
2) Communicate via asp.net webservices from the SWF directly to the webservice.
3) Not sure but could probably do a POST to a processing aspx page?
HTH
I think a good option is to use the XML class so consider this:
var xmlRequest = new XML();
xmlRequest.onLoad = parseXMLResponse;
xmlRequest.load("http://yourpathtoyourserver/file.aspx?listselectedvalue=something");
function parseXMLRequest(loaded)
{
trace("hi");
}
You can also have the page give you data back this way so it's not just one way communication.
Assuming you are using Action Script 2.
Read the important notes at the bottom of each codes pertain to sending and retrieving data from flash to .net page. Explanation of the code is in the comment inside the code.
Flash Part (Action Script 2)
//function to send collected form data to asp.net page
//use other control/button to call this function
//important: in order for the 'onLoad' event to work correctly, this function has to be 'Void'
function sendForm():Void
{
//create LoadVars object
var lv_in:LoadVars = new LoadVars();
var lv_out:LoadVars = new LoadVars();
//set onLoad event
lv_in.onLoad = function(success:Boolean)
{
//if success, meaning data has received from .net page, run this code
if (success)
{
//lv_in.status is use to get the posted data from .Net page
statusMsg.text = "Thank you for filling up the form!" + lv_in.status;
}
//if fail, run this code
else
{
statusMsg.text = "The form you are trying to fill up has an error!";
}
}
//this is the collected data from the form
lv_out.userName = txtUserName.text;
lv_out.userAddress = txtUserAddress.text;
lv_out.userBirthday = txtUserBirthday.text;
//begin invoke .net page
lv_out.sendAndLoad("ProcessDataForm.aspx", lv_in, "POST");
}
Important note:
The function that contain onLoad event, in this case sendForm function, has to be Void function, meaning it's not returning value. If this function return value, what happen is the function will be executed all the way without waiting for the returned data from .net page, thus the onLoad event will not be set properly.
.Net Part
public void ProcessData
{
//process the data here
Response.Write("status=processed&");
}
Important note:
To send data/message back to flash, you can use Response.Write. However, if you want Action Script to parse the posted message/data from .Net page keep in mind you have to include & symbol at the end of the message. When parsing data/message, Action Script will stop at & symbol, thus leave the rest of the message alone and only get the message under sent variable.

Resources