I'm trying to create my custom validation handler for some custom fields on workflow form. A have two fields: project begin date and project end date.
For those two field i need two types of validation:
project begin date can not be less then today's date
project end date must be equal or grater then project begin date
However i'm still on beginning of creation custom validation-handlers. For start i just tried some simple validation handler for text field with numbers only but this isn't functioning. I did the following:
In my share-config-custom.xml i add
<config>
<forms>
<dependencies>
<js src="/custom-form-validation.js" />
</dependencies>
</forms>
and connect to my field
<field id="mcwm:shortProjectNumber" set="general" mandatory="true">
<constraint-handlers>
<constraint type="MANDATORY" validation-handler="Alfresco.forms.validation.checkNumber" event="keyup" />
</constraint-handlers>
</field>
custom-form-validation.js file is
Alfresco.forms.validation.checkNumber = function checkNumber(field, args, event, form, silent, message) {
var ok = (field.value=="") || field.value.match("^\\d{4}\\/\\d{4}$");
var valid = ok != null && ok;
if (!valid) {
YAHOO.util.Dom.setStyle(field.id, "border", "2px solid red");
}
else {
YAHOO.util.Dom.setStyle(field.id, "border", "");
}
// Inform the user if invalid
if (!valid && !silent && form)
{
var msg = "The number must match the pattern 1234/5678.";
form.addError(form.getFieldLabel(field.id) + " " + msg, field);
}
return valid;
};
I put custom-form-validation.js file in my opt\tomcat\shared\classes\alfresco\web-extension folder, but there is no field validation at all? Any suggestion on this?
Regards,
Aleksadnar
Field validation in Share is implemented as client-side JavaScript. So your JavaScript file goes in the root of your web app (preferably a directory structure below that), not under WEB-INF. For example, you might want to put it under $TOMCAT_HOME/webapps/share/extension/js. You may have to adjust your dependencies reference accordingly.
Next, don't put custom code in Alfresco's namespace. Create your own. You can create your own namespace by placing something like this in the beginning of your JavaScript file:
if (typeof SomeCo == "undefined" || !SomeCo)
{
var SomeCo = {};
}
You may also want to minify your JavaScript. Then, turn on Share debug. You do that by placing the following in share-config-custom.xml (which lives under $TOMCAT_HOME/webapps/share/WEB-INF/classes/alfresco/web-extension):
<alfresco-config>
<!-- Put Share Client in debug mode -->
<config replace="true">
<flags>
<client-debug>false</client-debug>
<client-debug-autologging>false</client-debug-autologging>
</flags>
</config>
</alfresco-config>
With that in place you can use your browser's developer console to step through the client side JavaScript and figure out why your validator isn't working.
You can use an alternative way to implement the form field validation handler, using javascript directly. I mean, you can add a listener to control when the form is submitted, and add a condition to cancel the submition. So, you could use a code like this when the form is loaded:
//Add a listener to control when the form is submitted
document.body.addEventListener("submit", function (event) {
//If there are wrong values
if(wrongValues()){
//Cancel the event
event.stopPropagation();
event.preventDefault();
}
}, true);
If you want more details about this solution, you can visit this post
Related
I just started using SugarCRM CE for the first time (Version 6.5.15 (Build 1083)). I'm quite impressed with the ease of use when adding new fields or modules, but there's one quite indispensable thing that seems to be missing: Validation of user input.
I would for example like to check a lot of things:
Check if a emailadres has a valid format, using some regular expression
Check if a postalcode exists (maybe do a webswervice call to validate it)
Do a calculation to see if a citizen service number is valid
etc.
The only thing I seem to be able to do in studio is make a field required or not, there doesn't seem to be any standard way to execute a validation on a field.
All I can find when I google on it is lots of ways to hack into the source code, like this one: http://phpbugs.wordpress.com/2010/01/22/sugarcrm-adding-javascript-validation-on-form-submit/ And even then I don't find any examples that actually do a validation.
Am I just missing something? Or is editing source code the only way to add this?
I don't think the "standard" validations are available in the CE edition.
What surprises me is that you can't define a validation somewhere and attach it to a field. I kind of expected this, since the rest of the system is very well structured (modules, packages, etc..)
I now for instance created a 11-check, this is a very specific check for a dutch bank account number. to get this to work, I did the following (based upon examples I found googling around):
I added the bank account to contacts in studio and after that edited \custom\modules\Contacts\metadata\editviewdefs.php
I added the following snippets:
'includes'=> array(
array('file'=>'custom/modules/Contacts/customJavascript.js')),
array (
0 =>
array(
'customCode' =>
'<input title="Save [Alt+S]" accessKey="S" onclick="this.form.action.value=\'Save\'; return check_custom_data();" type="submit" name="button" value="'.$GLOBALS['app_strings']['LBL_SAVE_BUTTON_LABEL']>',
),
1 =>
array(
'customCode' =>
'<input title="Cancel [Alt+X]" accessKey="X" onclick="this.form.action.value=\'index\'; this.form.module.value=\''.$module_name.'\'; this.form.record.value=\'\';" type="submit" name="button" value="'.$GLOBALS['app_strings']['LBL_CANCEL_BUTTON_LABEL'].'">'
)
),
And in customJavascript.js i placed this code:
function check_custom_data()
{
if (!eleven_check(document.getElementById("bankaccount_c").value)){
alert ('Bank account not valid');
return false;
} else {
return check_form('EditView');
}
function eleven_check(bankaccount) {
bankaccount=bankaccount.replace(/\D/, "");
charcount=bankaccount.length;
var som=0;
for (i=1; i<10; i++) {
getal=bankaccount.charAt(i-1);
som+=getal*(10-i);
}
if (som % 11==0 && charcount==9) {
return true
} else {
return false
}
}
}
This check now works the way I want it to work, but I'm wondering if this is the best way to add a validation. this way of adding a validation doesn't however accommodate PHP validations, for instance, if I want to validate against some data in the database for one or another reason, I would have to use ajax calls to get that done.
Email validation is in the pro edition, I had assumed it was in CE as well but I'm not 100% sure.
The other 2 are a lot more specific - postcode validation would depend upon your country so would be difficult to roll out. For these you will need to write your own custom validation.
I know its late, but maybe still someone needs this.
You can just add your custom javascript validation as a callback in your vardefs like this:
'validation' =>
array (
'type' => 'callback',
'callback' => 'function(formname,nameIndex){if($("#" + nameIndex).val()!=999){add_error_style(formname,nameIndex,"Only 999 is allowed!"); return false;}; return true;}',
),
I documented it here as its not well documented elsewhere:
https://gunnicom.wordpress.com/2015/09/21/suitecrm-sugarcrm-6-5-add-custom-javascript-field-validation/
You can add custom validation code to the following file: ./custom/modules/.../clients/base/views/record/record.js
There you can add validation code. In this example, I will validate if the phone_number is not empty when an accounts has a customer-type:
EXAMPLE CODE IN RECORD.JS:
({
extendsFrom: 'RecordView',
initialize: function (options) {
app.view.invokeParent(this, {type: 'view', name: 'record', method: 'initialize', args:[options]});
//add validation
this.model.addValidationTask('check_account_type', _.bind(this._doValidateCheckType, this));
},
_doValidateCheckType: function(fields, errors, callback) {
//validate requirements
if (this.model.get('account_type') == 'Customer' && _.isEmpty(this.model.get('phone_office')))
{
errors['phone_office'] = errors['phone_office'] || {};
errors['phone_office'].required = true;
}
callback(null, fields, errors);
}
})
Don't forget to repair en rebuild!
The full documentation can be found here
I am using eventhandler on my Xpage to save my datasource (frmData):
<xp:eventHandler
id="saveEventHandler"
submit="true"
save="true"
event="calledbyid"
refreshMode="complete"
>
<xp:this.action><![CDATA[#{javascript:frmData.save();
context.redirectToPage("index.xsp")}]]></xp:this.action>
</xp:eventHandler>
This is called by custom properites:
<xe:basicLeafNode
onClick="XSP.executeOnServer('#{id:saveEventHandler}')"
label="Save"
rendered="#{javascript:currentDocument.isEditable()}"
>
</xe:basicLeafNode>
That is Mr. Jeremy Hodge code for client to server site trigger:
XSP.executeOnServer = function () {
// must supply event handler id or we're outta here....
if (!arguments[0])
return false;
// the ID of the event handler we want to execute
var functionName = arguments[0];
// OPTIONAL - The Client Side ID that you want to partial refresh after executing the event handler
var refreshId = (arguments[1]) ? arguments[1] : "#none";
var form = (arguments[1]) ? this.findForm(arguments[1]) : dojo.query('form')[0];
// catch all in case dojo element has moved object outside of form...
if (!form)
form = dojo.query('form')[0];
// OPTIONAL - Options object contianing onStart, onComplete and onError functions for the call to the
// handler and subsequent partial refresh
var options = (arguments[2]) ? arguments[2] : {};
// OPTIONAL - Value to submit in $$xspsubmitvalue. can be retrieved using context.getSubmittedValue()
var submitValue = (arguments[3]) ? arguments[3] : '';
// Set the ID in $$xspsubmitid of the event handler to execute
dojo.query('[name="$$xspsubmitid"]')[0].value = functionName;
dojo.query('[name="$$xspsubmitvalue"]')[0].value = submitValue;
this._partialRefresh("post", form, refreshId, options);
}
All fields value on the form has been save except one which is Rich text Item.
When I use simple button onclick event Instead of using above even handler, that Rich text Item saved!!
<xp:button
value="Label"
id="button1"
xp:key="facet_3"
>
<xp:eventHandler
event="onclick"
submit="true"
refreshMode="complete"
>
<xp:this.action>
<xp:saveDocument
var="frmData"
>
</xp:saveDocument>
</xp:this.action>
</xp:eventHandler>
</xp:button>
Please let me know how to handle this event handler?
-mak
I don't know if the issue is with the Rich Text Item or the method of submitting. One thing I notice is that you're only passing one parameter to XSP.executeOnServer(), so it's going to infer the submit ID and the submit value.
Can you use Firebug or something similar to check what content is being submitted back to the server, both when you click the button and during the rest of the XPage's life cycle? It's hard to troubleshoot the page lifecycle processes from a question.
If no submit ID or submit value is being passed back to the server, no datasources or components on the page will be updated when you click the button. It will just save the datasource with whatever values were stored against the datasource from previous partial refreshes.
Whenever a partial refresh is triggered, some content will be updated in the server-side map of the XPage. So any previous partial refreshes may update the datasource with values before the XSP.executeOnServer() is triggered. If values have been passed back to the datasource by a partial refresh, those will be saved because they're already in the datasource, not because they are passed again by the XSP.executeOnServer().
If Firebug shows a submit id or submit value that includes the datasource being passed back to the server, the values will be passed back to the datasource, in which case there could be an issue specific to Rich Text Items.
Enter/change something in a textarea
Before submitting the form, leave the page (e.g. by clicking browser's back button)
Go back to the edit page (e.g. by clicking the forward button)
Expected result: the content entered in the textarea should still be there
Actual result:
with HTTPS: all changes are gone (bad!)
with HTTP: the changes are still there (good!)
Why is this happening when using HTTPS? How can I prevent this? Is the browser or the website responsible?
You can consider the following solutions:
The autocomplete Attribute (HTML5)
This seems unrelated since autocomplete tells the browser to complete fields with the values based on earlier user input which were "submitted" with the form. But in my tests I saw that; after filling out the form without submitting; when I hit the forward (history) button and hit back again; form fields were auto-filled if I set autocomplete="on" and all were cleared when set to "off".
So; (if targeting HTML5 users) you can use this attribute to "cache" your form data. (Works on all major browsers, except Opera).
<form action="/update" method="post" autocomplete="on">
Email: <input type="text" id="email" /><br />
Username: <input type="text" id="uname" /><br />
Password: <input type="password" id="pwd" autocomplete="off"/><br />
<input type="submit" />
</form>
Notice that you can set the auto-complete feature off for a specific field (password in this case) when the rest of the form controls are on.
MSDN Remarks:
If the autocomplete attribute is missing, the field will default to an 'on' state if element has no parent form, or if the form has
autocomplete set to 'on'.
Information provided by the AutoComplete feature is not exposed to
the object model, and is not visible to a Web page until the user
selects one of the suggestions as a value for the text field.
Save the Un-submitted Form Data Locally:
You can store the input data locally, right before the page redirection or on focus-out event of every form control:
Cookies
The good-old cookies can come handy in this case but you should consider the down-sides:
Even though you can encrypt the values programmatically; since we will be working on the client-side, cookies are not truly secure for this. Http-Only and Secure marked cookies will not help us here, because these options are used to enforce SSL when the cookie is "sent" (secure) and cannot be accessed from Javascript (http-only).
Browsers have a cookie size limit. From MSDN: "Most browsers support
cookies of up to 4096 bytes. Because of this small limit, cookies
are best used to store small amounts of data". So, if you don't
watch for this size (when you write the cookie and/or by limiting
the control's value via maxlength attributes); that could be a
problem. (and trimming the value is the worst thing in this case).
Browsers also have a limit to the number of cookies that can be set
per domain. So; when storing the form data in the cookies; instead of setting cookies for each form field value; you should merge them into one or few cookies; for your site not to
exceed this limit.
Still, the bright side is they are supported by all browsers and if you don't plan to "cache" sensitive and too-long data via Cookies, then you can use the following solution. If this is not the case; you should better go with the next suggestion: localStorage.
// Below is just a demonstration and is not tested thoroughly for
// production-ready web applications by any means.
// But it should give you an idea.
/**
* Caches the user-input data from the targeted form, stores it in the cookies
* and fetches back to the form when requested or needed.
*/
var formCache = (function () {
var _form = null,
_formData = [],
_strFormElements = "input[type='text'],"
+ "input[type='checkbox'],"
+ "input[type='radio'],"
// + "input[type='password']," // leave password field out
+ "input[type='hidden'],"
// + "input[type='image'],"
+ "input[type='file'],"
// more input types...
+ "input[type='email'],"
+ "input[type='tel'],"
+ "input[type='url'],"
+ "select,"
+ "textarea";
function _warn() {
console.log('formCache is not initialized.');
}
return {
/**
* Initializes the formCache with a target form (id).
* You can pass any container id for the formId parameter, formCache will
* still look for form elements inside the given container. If no form id
* is passed, it will target the first <form> element in the DOM.
*/
init: function (formId) {
var f = (typeof formId === 'undefined' || formId === null || $.trim(formId) === '')
? $('form').first()
: $('#' + formId);
_form = f.length > 0 ? f : null;
console.log(_form);
return formCache; // make it chainable
},
/**
* Stores the form data in the cookies.
*/
save: function () {
if (_form === null) return _warn();
_form
.find(_strFormElements)
.each(function() {
var f = $(this).attr('id') + ':' + formCache.getFieldValue($(this));
_formData.push(f);
});
docCookies.setItem('formData', _formData.join(), 31536e3); // 1 year expiration (persistent)
console.log('Cached form data:', _formData);
return formCache;
},
/**
* Fills out the form elements from the data previously stored in the cookies.
*/
fetch: function () {
if (_form === null) return _warn();
if (!docCookies.hasItem('formData')) return;
var fd = _formData.length < 1 ? docCookies.getItem('formData').split(',') : _formData;
$.each(fd, function (i, item) {
var s = item.split(':');
var elem = $('#' + s[0]);
formCache.setFieldValue(elem, s[1]);
});
return formCache;
},
/**
* Sets the value of the specified form field from previously stored data.
*/
setFieldValue: function (elem, value) {
if (_form === null) return _warn();
if (elem.is('input:text') || elem.is('input:hidden') || elem.is('input:image') ||
elem.is('input:file') || elem.is('textarea')) {
elem.val(value);
} else if (elem.is('input:checkbox') || elem.is('input:radio')) {
elem.prop('checked', value);
} else if (elem.is('select')) {
elem.prop('selectedIndex', value);
}
return formCache;
},
/**
* Gets the previously stored value of the specified form field.
*/
getFieldValue: function (elem) {
if (_form === null) return _warn();
if (elem.is('input:text') || elem.is('input:hidden') || elem.is('input:image') ||
elem.is('input:file') || elem.is('textarea')) {
return elem.val();
} else if (elem.is('input:checkbox') || elem.is('input:radio')) {
return elem.prop('checked');
} else if (elem.is('select')) {
return elem.prop('selectedIndex');
}
else return null;
},
/**
* Clears the cache and removes the previously stored form data from cookies.
*/
clear: function () {
_formData = [];
docCookies.removeItem('formData');
return formCache;
},
/**
* Clears all the form fields.
* This is different from form.reset() which only re-sets the fields
* to their initial values.
*/
clearForm: function () {
_form
.find(_strFormElements)
.each(function() {
var elem = $(this);
if (elem.is('input:text') || elem.is('input:password') || elem.is('input:hidden') ||
elem.is('input:image') || elem.is('input:file') || elem.is('textarea')) {
elem.val('');
} else if (elem.is('input:checkbox') || elem.is('input:radio')) {
elem.prop('checked', false);
} else if (elem.is('select')) {
elem.prop('selectedIndex', -1);
}
});
return formCache;
}
};
})();
// Save form data right before we unload the form-page
$(window).on('beforeunload', function (event) {
formCache.save();
return false;
});
// Initialize and fetch form data (if exists) when we load the form-page back
$(document).on('ready', function (event) {
formCache.init().fetch();
});
Here is a working demo on jsFiddle.
Note: The "cookies reader/writer" script from developer.mozilla.org should be included with the code above. You can also use Yahoo's YUI 2: Cookie Utility which has a useful setSub() method for setting sub-cookies inside a single cookie, for the browser limit that I previously mentioned.
localStorage
You can also use more modern techniques like localStorage (HTML5). It is more secure and faster. All major browsers support this feature including IE 8+. (Additionally, iOS and Android support!)
if (typeof Storage !== 'undefined') { // We have local storage support
localStorage.username = 'Onur'; // to save to local storage
document.getElementById('uname').value = localStorage.username; // to fetch from local storage
}
So, just like in the cookies example;
$(window).on('beforeunload', function (event) {
saveFormToLocalStorage();
return false;
});
$(document).on('ready', function (event) {
fillFormFromLocalStorage()
});
SessionStorage
This works pretty much the same way. From W3C: The sessionStorage object is equal to the localStorage object, except that it stores the data for only one session.
Save Form Data to Server/DB via Silent AJAX Post(s):
Not a very efficient way but you might want to use this where others are not feasible. You can make the post on the beforeunload event and prompt a message to the user.
$(window).on('beforeunload', function (event) {
//check if at least one field is filled out.
//make the AJAX post if filled out.
return "You are leaving the page without submitting the form...";
});
Retrieve Previously Saved Data from Server on Page Load:
Just to remind you; if the user is filling out an "update" form, for example; you can always fetch the previously saved data from the server and automatically fill in the form (non-sensitive fields).
Conclusion
If you really need this and worth the trouble; you should consider a cross-browser solution that implements a fall-back mechanism; such as:
IF you have support for HTML5 features; use HTML5 autocomplete
attribute. (You can embed the attribute in the HTML beforehand, or
set it via Javascript/jQuery when you test for browser support.)
ELSE IF you have support for the Storage object; go with
localStorage;
ELSE IF [cookies your current session stores] + [cookie size your
form data needs] < 4096 bytes; then use cookies.
ELSE IF you have a server-side web-app make silent AJAX requests to
store data on server.
ELSE don't do it.
Note: For HTML5 feature detection, take a look at this page or this page or you can use Modernizr.
HTTPS Problem:
The reason, all form changes are gone when using HTTPS is that; it is a secure protocol. Forms are mostly used for user input and can (probably) contain sensitive data. So this behavior seems natural and expected. The solution(s) I offer above will work the same as they do on HTTP. So that should cover all your concerns.
Further reading:
Autofilling form controls: the autocomplete attribute
HTML5 form autocomplete attribute
DOM Storage
HTML5 Web Storage
Future of Local Storage for Web
Cookies
This is what worked for me.
<select
class="form-select custom-select page-number-select"
(change)="onPageChange($event)"
data-test="XXXX"
[attr.aria-labelledby]="XXXX"
[value]="pageNumber" <---- This fixed the problem
>
<ng-container
*ngFor="let pageNumber of totalPageCount"
>
<option value="{{ pageNumber }}" [attr.selected]="pageNumber == page ? '' : null" >
{{ t('pageN', { pageNumber: pageNumber }) }}
</option>
</ng-container>
</select>
Adding the data coming from the stream in the value attribute ensured that the correct value is shown at all times. Even upon browser's popstate events (back and forward button clicks)
I am iterating through some data and generating parameterized URL links based on some conditions like this:
finishedHTML.append("<a href=\"http://" + domain + "&service=" + allEvents[eventCounter].EventService +"&day="+ offSet+(-1 * i) +"\"><img src=\"/info.jpg\" alt=\"Info\"/>");
I had the beginning of my application checking for URL parameters when the page was loaded/refreshed, and take some action depending on if the parameters were there and what they were.
However, I added a # to the beginning of the paramters, so the page wouldn't need to be refreshed, but now it's not triggering the function that checks the URL.
My question is how can I trigger an event in GWT when a user clicks a link? Do I need to generate GWT controls, and link a click handler? Is it possible to setup an event that fires when the URL is changed???
UPDATE:
Adam answered part of the initial question, but I can't get the querystring after "#". Is there a better way than the function below:
public static String getQueryString()
{
return Window.Location.getQueryString();
}
In other words, if I enter example.com?service=1 I get service=1 as my querystring. If I enter example.com#?service=1, I get a null value for the querystring..
Use History.addValueChangeHandler( handler ), and create a handler to catch the URL changes.
There's no need for click handlers etc., any change of the "hash" part in the URL will be sufficient.
EDIT:
See this code example - it will parse URLs of the form http://mydomain/my/path#tok1&tok2&tok3
public void onValueChange(ValueChangeEvent<String> event) {
String hash = event.getValue();
if ( hash.length() == 0 ) {
return;
}
String[] historyTokens = hash.split("&",0);
// do stuff according to tokens
}
(Just responding to your Update)
Have you tried
History.getToken()
to get the value after the "#"?
I have an asyncfileupload control that I'm using from the ajaxcontroltoolkit. On the file complete in the code behind I process the file and write the information in the file to a database. I get the id of the record from the database, and this needs to be written to an asp hidden field. I've tried just setting the value:
fldImageID.Value = pimg.IdImageGroup.ToString();
I've tried Registering a script like I've seen in an example on a website:
ScriptManager.RegisterClientScriptBlock(
ImageFileUploader,
ImageFileUploader.GetType(),
"script1",
"alert('hi'); top.document.getElementById('"
+ fldImageID.ClientID
+ "').value='"
+ pimg.IdImageGroup.ToString()
+ "'; top.document.getElementById('"
+ lblError.ClientID
+ "').innerHTML = 'image uploaded'",
true);
I've just tried embedding javascript in a response.Write call from the method I've set to process the uploaded file. Nothing I've done has worked so far. After I've done everything the hidden field still does not contain the required value.
This is pretty easy with jQuery. Have an html hidden input control placed in your page, not the asp:hidden input control. Add a class lets say "hiddenPhoto" to your html hidden control.
so lets say our control html is like this
<input type="hidden" class="hiddenPhoto" runat="server" id="hdPhotoName" />
Now access it using class selector in your OnClientUploadComplete js method and set its value. Have it declared runat="server" in order to access its value on the server side.
Regards
I found an acceptable solution back when I was working on this. And since then I've received emails from people who have had the same problem and have been asking if I found a solution. So I'm presenting it here, stripping out any extraineous code:
From the user control that has the FileUpload control I first set the session variable on the back side in the FileUploadComplete handler:
*in the ascx file (upload_chart.ascx) I have the AsyncFileUpload, what is important is the OnUploadComplete and the OnClientUploadComplete:*
<ajaxToolkit:AsyncFileUpload
OnUploadedComplete="FileUploadComplete1"
OnClientUploadComplete="UploadComplete1"
ID="ImageFileUploader"
runat="server" />
*in the code behind of the ascx file (upload_chart.ascx.cs) I handle the FileUploadComplete:*
public void FileUploadComplete1(object sender, EventArgs e)
{
try
{
if (ImageFileUploader.FileBytes.Length > 0)
{
// File data is in ImageFileUploaded.FileBytes
// Save it however you need to
// I saved it to a database, in a DBImage Object class I created
// DBImage is specific to my application
ODS.Entity.DBImage pimg =
ODS.Data.DataRepository.SaveImageBytes(ImageFileUploaded.FileBytes);
// Set the ImageID1 in the session
Session["ImageID1"] = pimg.IdImageGroup.ToString();
}
else
{
// error handling for an empty file, however you want to handle it
}
}
catch (Exception Ex)
{
// error handling for an unhandled exception, whatever you want to do here
}
}
Javascript and script methods are used to set the value on the page, here is my codebehind for the script method:
// on the aspx page code behind (chartofthedayadmin.aspx.cs) I have the webmethod:
[System.Web.Services.WebMethod]
public static string GetImageID1()
{
System.Web.SessionState.HttpSessionState Session = System.Web.HttpContext.Current.Session;
String retval = Session["ImageID1"].ToString();
Session["ImageID1"] = null;
return retval;
}
Here is the javascript:
// on the aspx front end (chartofthedayadmin.aspx) I have the javascript
// to call the Web method and the javascript failed message:
function UploadComplete1() {
var str = PageMethods.GetImageID1(uploadSuccess1, uploadFailed);
}
function uploadFailed() {
alert('error occurred or some meaningfull error stuff');
}
*// javascript on the user control (upload_chart.ascx) to set the value of the hidden field*
function uploadSuccess1(result) {
document.getElementById('<%= fldImageID.ClientID %>').value = result;
}
note: Make sure your scriptmanager has EnablePageMethods="true".
The better and more simple solution is in code behind:
string script = String.Format("top.document.getElementById('hdnFilename').value='{0}';", safeFilename);
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "hdnFilenameFromCodeBehind", script, true);
In my case, safeFilename is the unique filename, after handling duplicate filename, i.e. sample_5.png in the 5th upload of sample.png.
See http://forums.asp.net/t/1503989.aspx