What triggers a CustomValidator with a ClientValidationFunction? - asp.net

I am using a customValidator to validate whether a date is within a valid range or not within a textbox. It works great if you manually enter in a date and calls my custom ClientValidationFunction. Unfortunately if i use a popup calendar to select a date my customValidator is not triggered.
I was hoping to get a better understanding on how asp:CustomValidators are triggered.
I've tried to force input validation to re-validate when the calendar is closed but have had no luck.
<asp:CustomValidator ID="ValidDateCheck" runat="server" ControlToValidate="txtDate" ErrorMessage="Please enter a valid date." ClientValidationFunction="clientValidate"
EnableClientScript="True" Display="Dynamic" CssClass="dateboxRJS-validator text-danger" ValidateEmptyText="true"></asp:CustomValidator>
Javascript
clientValidate = function (source, args) {
console.log("validating...");
var s = document.getElementById(source.controltovalidate);
var minDate = moment("1900-01-01");
var maxDate = moment().add(200, 'y');
var inputDate;
if (moment(s.value, "MM/DD/YYYY", true).isValid()) {
inputDate = moment(s.value, "MM/DD/YYYY");
console.log(s.value);
console.log("break");
if (!inputDate.isBetween(minDate, maxDate)) {
args.IsValid = false;
s.classList.add("is-invalid");
Page_BlockSubmit = true;
return false;
} else {
s.classList.remove("is-invalid");
args.IsValid = true;
Page_BlockSubmit = false;
return true;
}
}
}
});

Related

Why is Regular Expression Not working in .NET

Why would a regular expression not work in an ASP.net application when it is working in online regex?
I tried to implement the same code in ASP.net but it is not working properly. Can anyone figure out these problem?
Unrestricted File Upload as
The application should use a whitelist of allowed file types. This list determines the types of files that can be uploaded and rejects all files that do not match approved types.
The application should use server-side input validation to ensure evasion techniques have not been used to bypass the whitelist filter. These evasion techniques could include appending a second file type to the file name (e.g. image.jpg.php) or using trailing space or dots in the file name.
Only alphanumeric characters and Hyphen should be allowed in the filename.
<asp:RegularExpressionValidator ID="Rg_FrontPage" ValidationExpression="^(\[a-z\]|\[A-Z\]|\[0-9\]|\[-\]|\[(0-9)+\]+)+\.(jpg|JPG|JPEG|jpeg|png|PNG)$"
ControlToValidate="FUp_Front" runat="server" Font-Size="Small" ForeColor="Red"
ErrorMessage="Max size 100KB. Upload only JPEG/JPG/PNG format" ValidationGroup="Submit"
Display="Dynamic" />
An alternative: You could perform the check in the Click event where you could validate the file name (i.e. FUp_Front.FileName) or better the content type (i.e. FUp_Front.PostedFile.ContentType) of the uploaded file. See the FileUpload control tutorial and the Uploading Files (C#) documentation for further information.
To fix the regex:
You don't need to escape the brackets in your regex, e.g. (a little simplified version):
<asp:RegularExpressionValidator ID="Rg_FrontPage" ValidationExpression="^[a-zA-Z0-9.-]+(jpg|JPG|JPEG|jpeg|png|PNG)$" ViewStateIgnoresCase="true"
ControlToValidate="FUp_Front" runat="server" Font-Size="Small" ForeColor="Red"
ErrorMessage="Max size 100KB. Upload only JPEG/JPG/PNG format" ValidationGroup="Submit"
Display="Dynamic" />
See the docs for further information.
i am using javacript method in client side which is solve my problems onclientclick i do not know why regular expression is fails
<asp:ImageButton ID="btnGenerateOtp" runat="server" ImageUrl="images_new/generate_new.jpg" OnClientClick="return complainformvalidate();"ValidationGroup="Submit
" OnClick="btnGenerateOtp_Click" Visible="false" />
function complainformvalidate() {
var flg = true;
if (document.getElementById('<%=FUp_Front.ClientID %>') != null) {
var fu1 = document.getElementById('<%=FUp_Front.ClientID %>').value;
if (fu1 != '') {
if (fu1.split(".").length - 1 > 1) {
document.getElementById('lblFUp_Front').innerHTML = 'Please enter valid file';
document.getElementById('lblFUp_Front').style.color = "red";
document.getElementById('<%=CV_FUp_Front.ClientID %>').style.display = 'none';
flg = false;
}
if (fu1.split(" ").length - 1 > 0) {
//alert('Inavlid file');
document.getElementById('lblFUp_Front').innerHTML = 'Please enter valid file';
document.getElementById('lblFUp_Front').style.color = "red";
document.getElementById('<%=CV_FUp_Front.ClientID %>').style.display = 'none';
flg = false;
}
var filenameWithExtension = fu1.replace(/^.*[\\\/]/, '');
var num = filenameWithExtension;
var pattern = /(^([a-z]|[A-Z]|[0-9]|[-]|[(0-9)+]+)+\.(jpg|JPG|JPEG|jpeg|png|PNG)$)/;
if (num.search(pattern) == -1) {
document.getElementById('lblFUp_Front').innerHTML = 'Please enter valid file';
document.getElementById('lblFUp_Front').style.color = "red";
document.getElementById('<%=CV_FUp_Front.ClientID %>').style.display = 'none';
flg = false;
}
}
}
<asp:ImageButton ID="btnGenerateOtp" runat="server" ImageUrl="images_new/generate_new.jpg" OnClientClick="return complainformvalidate();"
ValidationGroup="Submit" />
}
on server side i have use custom validator which is solve my problmes
<asp:CustomValidator ID="CV_FUp_Front" runat="server" ErrorMessage="Max size 100KB. Upload only JPEG/JPG/PNG format"
ClientValidationFunction="ValidateFile" OnServerValidate="ValidateFile_FUp_Front" Display="Dynamic" ValidationGroup="Submit"
Font-Size="8pt" CssClass="error errorMsg" />
protected void ValidateFile_FUp_Front(object source, ServerValidateEventArgs args)
{
int sizeinbytes_, fileSize_;
string fileName = "";
FileInfo fi;
string ext;
//added by santosh on 25Feb2020 prevent file is accept double extension
var regex = #"(^([a-z]|[A-Z]|[0-9]|[-]|[(0-9)+]+)+\.(jpg|JPG|JPEG|jpeg|png|PNG)$)";
var match = Regex.Match(FUp_Front.FileName, regex, RegexOptions.IgnoreCase);
if (!match.Success)
{
args.IsValid = false;
CV_FUp_Front.ErrorMessage = "Please enter valid file";
Rg_FrontPage.Enabled = false;
Rg_BackPage.Enabled = false;
}
int FUp_Front_count = FUp_Front.FileName.Split('.').Length - 1;
if (FUp_Front_count > 1)
{
args.IsValid = false;
CV_FUp_Front.ErrorMessage = "Please enter valid file";
}
//end by santosh
if (Session["FUp_Front"] == null && !FUp_Front.HasFile)
{
args.IsValid = false;
CV_FUp_Front.ErrorMessage = "Max size 100KB. Upload only JPEG/JPG/PNG format";
Rg_FrontPage.Enabled = false;
Rg_BackPage.Enabled = false;
}
else if (FUp_Front.HasFile)
{
fileName = FUp_Front.PostedFile.FileName;
fi = new FileInfo(FUp_Front.PostedFile.FileName);
ext = fi.Extension.ToLower();
if (ext != ".jpg" && ext != ".jpeg" && ext != ".png")
{
args.IsValid = false;
CV_FUp_Front.ErrorMessage = "Max size 100KB. Upload only JPEG/JPG/PNG format";
Rg_FrontPage.Enabled = false;
Rg_BackPage.Enabled = false;
}
sizeinbytes_ = FUp_Front.PostedFile.ContentLength;
fileSize_ = sizeinbytes_ / 1024;
if (fileSize_ > 100)
{
args.IsValid = false;
CV_FUp_Front.ErrorMessage = "Max size 100KB. Upload only JPEG/JPG/PNG format";
Rg_FrontPage.Enabled = false;
Rg_BackPage.Enabled = false;
}
}
else
{
args.IsValid = true;
}
}

how to pass id of a label to a function in c#.net

i have the following label.
<asp:Label ID="lbl_Modification" runat="server" Font-Bold="False" Font-Size="Small" ForeColor="#FF3300" Visible="False" Width="300px"></asp:Label>
<asp:Label ID="lbl_Message" runat="server" Font-Bold="False" Font-Size="Small" ForeColor="#FF3300" Visible="False" Width="300px"></asp:Label>
i want to pass id of the above label to the following method.
public bool date_Validation(DateTime t_Start_Date,DateTime t_End_Date,DateTime t_View_From)
{
#region date_Validation
try
{
if (t_Start_Date.Date < DateTime.Today)
{
lbl_Modification.Visible = true;
lbl_Modification.Text = "Date cannot be lesser than the Current Date";
return false;
}
else if (t_End_Date.Date < t_Start_Date)
{
lbl_Modification.Visible = true;
lbl_Modification.Text = "Invalid End Date";
return false;
}
else if (t_View_From.Date < DateTime.Today || t_View_From.Date >= t_Start_Date.Date)
{
lbl_Modification.Visible = true;
lbl_Modification.Text = "view Date cannot be greater than the Start Date or lesser than Current date";
return false;
}
return true;
}
catch (Exception e)
{
throw e;
}
#endregion
}
How i can i do this.
Please someone help me to do this.
public bool date_Validation(DateTime t_Start_Date,DateTime t_End_Date,DateTime t_View_From, Label lblModification)
{
// Method Content
}
//Call this method with your label parameter
date_Validation(startdate,enddate,viewform,lbl_Modification)
//lbl_Modification -> its your label name
Control's ID is a string, if you want to pass it as an extra parameter then change your method declaration to accept an additional param
public bool date_Validation(DateTime t_Start_Date,DateTime t_End_Date,DateTime t_View_From, string LabelID)
{
#region date_Validation
try
{
if (t_Start_Date.Date < DateTime.Today)
{
//Find the control here
var label=This.FindControl(LabelID);
lbl_Modification.Visible = true;
lbl_Modification.Text = "Date cannot be lesser than the Current Date";
return false;
}
else if (t_End_Date.Date < t_Start_Date)
{
lbl_Modification.Visible = true;
lbl_Modification.Text = "Invalid End Date";
return false;
}
else if (t_View_From.Date < DateTime.Today || t_View_From.Date >= t_Start_Date.Date)
{
lbl_Modification.Visible = true;
lbl_Modification.Text = "view Date cannot be greater than the Start Date or lesser than Current date";
return false;
}
return true;
}
catch (Exception e)
{
throw e;
}
#endregion
}
then your calling code would be something like
var isValid=date_Validation(startdate, enddate, "lbl_Modification");

Check if two dates are in same month

How do you check if the two dates are in a same month and year? And which validation control should I use to have this? I'm thinking of using client-side validation (if it's possible)
Thanks!
You could use a CustomValidator
aspx:
<asp:CustomValidator runat="server"
ID="valMonth"
onservervalidate="ServerValidation"
onclientvalidate="ClientValidate"
ErrorMessage="From and To must be in the same month" />
servervalidate:
protected void ServerValidation (object source, ServerValidateEventArgs args)
{
DateTime dtFrom;
DateTime dtTo;
if(DateTime.TryParse(TxtFrom.Text, out dtFrom) && DateTime.TryParse(TxtTo.Text, out dtTo))
{
args.IsValid = dtFrom.Year == dtTo.Year && dtFrom.Month == dtTo.Month;
}
else
{
args.IsValid = false;
}
}
You should also add two CompareValidators which check if both are valid dates.
To provide a ClientValidationFunction you can have a look at the getMonth and getFullYear functions.
For example(not tested):
<script language="javascript">
<!--
function ClientValidate(source, arguments)
{
var txtFrom = document.getElementById('<%= TxtFrom.ClientID %>');
var txtTo = document.getElementById('<%= txtTo.ClientID %>');
var dtFrom = new Date(txtFrom.value);
var dtTo = new Date(txtTo.value);
var monthFrom = dtFrom.getMonth();
var monthTo = dtTo.getMonth();
var yearFrom = dtFrom.getFullYear();
var yearTo = dtTo.getFullYear();
arguments.IsValid = yearFrom == yearTo && monthFrom == monthTo;
}
// -->
</script>
Assuming the date is in "dd/MM/yyyy" format, you could use this javascript function with a custom validator.
aspx
<asp:CustomValidator ID="CustomValidator1" runat="server"
EnableClientScript="true"
ErrorMessage="ERROR MESSAGE HERE"
ClientValidationFunction="checkDate">
</asp:CustomValidator>
javascript
function checkDate() {
var date1=document.getElementById('<%=txtDate1.ClientID%>').value;
var date2=document.getElementById('<%=txtDate1.ClientID%>').value;
var date1Values=date1.split("/");
var date2Values=date2.split("/");
if (date1Values[2] == date2Values[2] && date1Values[1] ==date2Values[1]) {
args.IsValid = true;
}
else
{
args.IsValid = false;
}
}
You should have server validate code too if javascript is disabled. See Tim's answer.
Here's a short and simple example using a CustomValidator control
Date 1<asp:TextBox ID="txtDate1" runat="server" />
<br />
Date 2<asp:TextBox ID="txtDate2" runat="server" />
<br />
<asp:Button ID="btnCompare" runat="server" Text="Compare" />
<asp:CustomValidator ID="dateValidator" runat="server" ErrorMessage="The two dates must be in the same month and year"
OnServerValidate="ValidateDate" />
<script runat="server">
protected void ValidateDate(object source, ServerValidateEventArgs args)
{
DateTime date1 = DateTime.Parse(txtDate1.Text);
DateTime date2 = DateTime.Parse(txtDate2.Text);
if (date1.Month != date2.Month || date1.Year != date2.Year)
args.IsValid = false;
}
</script>

check/uncheckbox in gridview tracking

i have a below gridview control with a checkbox on it, so my question is when i hit on save button i able to find the checkbox which have been checked and till here no problem, but the problem started when the user tries to uncheck the checkedbox so how would i track the changes and save it into the db that has been checked. anyhelp?
List<Employee> result = new List<Employee>();
long Id = (long)Session["Id"];
result = Employee.GetEmployeeById(Id);
foreach (GridViewRow row in gv.Rows)
{
CheckBox chkBox = row.FindControl("chkSelected") as CheckBox;
if (c != null)
{
if (result.Count > 0)
{
foreach (Employee item in result)
{
Label Id = row.FindControl("lblId") as Label;
if (Id.Text == item.Id.ToString())
{
chkBox.Checked = true;
}
else
{
chkBox.Checked = false;
}
}
}
<asp:TemplateField HeaderText="Select">
<ItemTemplate>
<asp:CheckBox ID="chkSelected" runat="server" Checked="false"></asp:CheckBox>
</ItemTemplate>
</asp:TemplateField>
<script language="javascript" type="text/javascript">
function SelectAll(cb)
{
var gvVar = document.getElementById("<%= gv.ClientID %>");
var cell;
if (gvVar.rows.length > 0)
{
for (i=1; i<gvVar.rows.length; i++)
{
cell = gvVar.rows[i].cells[0];
for (j=0; j<cell.childNodes.length; j++)
{
if (cell.childNodes[j].type =="checkbox")
{
cell.childNodes[j].checked = document.getElementById(cb).checked;
}
}
}
}
}
//--------------------------------------------------------------------------------------------.
function Select(cb)
{
var total = parseInt('<%= this.gv.Rows.Count %>');
var counter=0;
var cbSelectAll=document.getElementById(cb);
var gvVar = document.getElementById("<%= gv.ClientID %>");
var cell;
if (gvVar.rows.length > 0)
{
for (i=1; i<gvVar.rows.length; i++)
{
cell = gvVar.rows[i].cells[0];
for (j=0; j<cell.childNodes.length; j++)
{
if (cell.childNodes[j].type =="checkbox")
{
if(cell.childNodes[j].checked)
counter++;
else
counter--;
}
}
}
}
if(counter==total)
cbSelectAll.checked=true;
else if(counter<total)
cbSelectAll.checked=false;
}
</script>
//----------------------------------------------------------------------------------------
protected void gv_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow && (e.Row.RowState == DataControlRowState.Normal || e.Row.RowState == DataControlRowState.Alternate))
{
CheckBox cbSelect = (CheckBox)e.Row.Cells[0].FindControl("cbSelect");
CheckBox cbSelectAll = (CheckBox)this.gv.HeaderRow.FindControl("cbSelectAll");
cbSelect.Attributes.Add("onclick", "javascript:Select('" + cbSelectAll.ClientID + "')");
cbSelectAll.Attributes.Add("onclick", "javascript:SelectAll('" + cbSelectAll.ClientID + "')");
}
}
Yes, store the original value in a hidden field. If always starting with false, you could use JavaScript to set the hidden value to true when the user clicked the checkbox. Using JQuery, you could do:
<asp:TemplateField HeaderText="Select" ItemStyle-CssClass="Checked">
<ItemTemplate>
<asp:CheckBox ID="chkSelected" runat="server" Checked="false"></asp:CheckBox>
<asp:HiddenField iD="dh" runat="server" />
</ItemTemplate>
</asp:TemplateField>
$("#<%= Grid.ClientID %>").find(".Checked > :checkbox").each(function() {
$(this).siblings("input[type='hidden']").attr("value", "True");
});
Something like that. On Server side, parse the value and if true, then you know it changed.
HTH.
It may not be the brightest idea, but you can query the database for the current state, and the compare with what you have got from the web page during a postback button click, or something like that. Or you can go with Brians answer.
It is possible to persist a list of objects into the Viewstate and access it in a consequent postback. The only thing is that the object you are trying to persist must be defined as serializable.
Update:
The ViewState approach
I feel this may be suitable for your need, and it requires a bit of linq. You'd need to create a class as follows:
[Serializable()]
public class OptionState
{
//the id of the item
int ID {get;set;}
//state of the checkbox
bool Checked {get;set;}
}
Note the Serializable attribute. This is required for the instance to persist to the viewstate.
Add the list of options to the viewstate:
var lstOptions = (from x in <your_option_store>
select new OptionState{ID = x.ID, Checked = x.Checked}).ToList();
ViewState.Add("options", lstOptions);
Here is a bit of code that should go into your button click:
foreach(GridViewRow row in gvOptions.Rows)
{
//not writing the bit of code
//which gets the ID and the
//state of checkbox of
//the gridview row being processed
OptionState currentState = GetOptionStateObjectFromRow(row);
List<OptionState> lstStates = (List<OptionState>) ViewState["options"];
OptionState originalState = lstStates.FirstOrDefault(x => x.ID == currentState.ID);
if(currentState.Checked != originalState.Checked)
{
//the appropriate db call needs to be done here.
}
}

Get HTML dynamic input value ASP.NET

I'm using jQuery's AutoComplete on an ASP.NET DropDownList, the user can select a value and submit for entry into the DB. But they must also be able to type in a value, and I can't seem to be able to access that value in the code behind.
Heres the jQuery:
(function ($) {
$.widget("ui.combobox", {
_create: function () {
var self = this,
select = this.element.hide(),
selected = select.children(":selected"),
value = selected.val() ? selected.text() : "";
var input = this.input = $("<input id='txtOptValue'>")
.insertAfter(select)
.val(value)
.autocomplete({
delay: 0,
minLength: 0,
source: function (request, response) {
var matcher = new RegExp($.ui.autocomplete.escapeRegex(request.term), "i");
response(select.children("option").map(function () {
var text = $(this).text();
if (this.value && (!request.term || matcher.test(text)))
return {
label: text.replace(
new RegExp(
"(?![^&;]+;)(?!<[^<>]*)(" +
$.ui.autocomplete.escapeRegex(request.term) +
")(?![^<>]*>)(?![^&;]+;)", "gi"
), "<strong>$1</strong>"),
value: text,
option: this
};
}));
},
select: function (event, ui) {
ui.item.option.selected = true;
self._trigger("selected", event, {
item: ui.item.option
});
},
change: function (event, ui) {
if (!ui.item) {
var matcher = new RegExp("^" + $.ui.autocomplete.escapeRegex($(this).val()) + "$", "i"),
valid = false;
select.children("option").each(function () {
if ($(this).text().match(matcher)) {
this.selected = valid = true;
return false;
}
});
if (!valid) {
// remove invalid value, as it didn't match anything
//$(this).val("");
// select.val("");
// input.data("autocomplete").term = "";
return false;
}
}
}
})
.addClass("ui-widget ui-widget-content ui-corner-left");
input.data("autocomplete")._renderItem = function (ul, item) {
return $("<li></li>")
.data("item.autocomplete", item)
.append("<a>" + item.label + "</a>")
.appendTo(ul);
};
this.button = $("<button type='button'> </button>")
.attr("tabIndex", -1)
.attr("title", "Show All Items")
.insertAfter(input)
.button({
icons: {
primary: "ui-icon-triangle-1-s"
},
text: false
})
.removeClass("ui-corner-all")
.addClass("ui-corner-right ui-button-icon")
.click(function () {
// close if already visible
if (input.autocomplete("widget").is(":visible")) {
input.autocomplete("close");
return;
}
// work around a bug (likely same cause as #5265)
$(this).blur();
// pass empty string as value to search for, displaying all results
input.autocomplete("search", "");
input.focus();
});
},
destroy: function () {
this.input.remove();
this.button.remove();
this.element.show();
$.Widget.prototype.destroy.call(this);
}
});
})(jQuery);
So this takes my DropDownList, hides it, creates an input field acting as my select and also enables me to type in values.. This is my DropDownList:
<asp:FormView ID="frmCreateOptionValue" runat="server" DataKeyNames="OptionValueID"
DataSourceID="OptionSetValues_DS" DefaultMode="Insert"
oniteminserting="frmCreateOptionValue_ItemInserting">
<InsertItemTemplate>
<table border="0" cellpadding="0" cellspacing="0" id="id-form">
<tr>
<th>
Add Option Set Value:
</th>
<td>
<div class="ui-widget" runat="server" id="addOptValue">
<asp:DropDownList ID="ddlAddOptionValue" runat="server" ClientIDMode="Static" DataSourceID="OptionValues_DS"
DataTextField="Name" DataValueField="OptionValueID" AppendDataBoundItems="true"
SelectedValue='<%# Bind("OptionValueID") %>'>
<asp:ListItem Value="" Text="Select One..." />
</asp:DropDownList>
<asp:ObjectDataSource ID="OptionValues_DS" runat="server" OldValuesParameterFormatString="original_{0}"
SelectMethod="GetDataBy1" TypeName="PurekbbDataSetTableAdapters.tblOptionValueTableAdapter">
<SelectParameters>
<asp:QueryStringParameter Name="oID" QueryStringField="optionSetID" Type="Int32" />
</SelectParameters>
</asp:ObjectDataSource>
</div>
</td>
<td>
<asp:LinkButton ID="InsertButton" runat="server" CausesValidation="True" CommandName="Insert"
CssClass="form-submit" />
</td>
</tr>
</table>
</InsertItemTemplate>
</asp:FormView>
And when the user inserts an item:
protected void OptionSetValues_DS_Inserting(object sender, ObjectDataSourceMethodEventArgs e)
{
// if the value doesn't already exist, create it
if (e.InputParameters["OptionValueID"] == null)
{
// !!!! CANNOT FIND THE HTML INPUT AND SAVE THE VALUE
string ovName = ((TextBox)frmCreateOptionValue.FindControl("txtOptValue")).Text;
int ovOptionID = Convert.ToInt32(Request.QueryString["OptionSetID"]);
tblOptionValueTableAdapter t = new tblOptionValueTableAdapter();
int ovID = Convert.ToInt32(t.InsertQuery(ovOptionID, ovName, 0, ""));
e.InputParameters["OptionValueID"] = ovID;
}
}
Is where I am stuck, how can I get the value from that HTML input field generated in jQuery?
How can this be achieved, it's killing me ;)
you can get the value of this text box using javascript and save it in a hidden field then read the hidden field value from code behind
put this inside javascript
$('#HiddenFieldID').val($('#txtOptValue').val());
then code behind will look like this
protected void OptionSetValues_DS_Inserting(object sender, ObjectDataSourceMethodEventArgs e)
{
// if the value doesn't already exist, create it
if (e.InputParameters["OptionValueID"] == null)
{
// !!!! CANNOT FIND THE HTML INPUT AND SAVE THE VALUE
string ovName = ((HiddenField)frmCreateOptionValue.FindControl("HiddenFieldID")).Value;
int ovOptionID = Convert.ToInt32(Request.QueryString["OptionSetID"]);
tblOptionValueTableAdapter t = new tblOptionValueTableAdapter();
int ovID = Convert.ToInt32(t.InsertQuery(ovOptionID, ovName, 0, ""));
e.InputParameters["OptionValueID"] = ovID;
}
}
Heres the solution to this one, using a HiddenField:
Add onblur to the dynamically created input:
(function ($) {
$.widget("ui.combobox", {
_create: function () {
var self = this,
select = this.element.hide(),
selected = select.children(":selected"),
value = selected.val() ? selected.text() : "";
var input = this.input = $("<input id='txtOptValue' onblur='JavaScript:copyValue()'>") ....
Add HiddenField and jQuery to the page:
<asp:HiddenField runat="server" ID="hfoValue" EnableViewState="true" ClientIDMode="Static" />
<div class="ui-widget" runat="server" id="addOptValue">
<script type="text/javascript" language="javascript">
function copyValue() {
var theVal = $('#txtOptValue').val();
//alert('Copyng ' + theVal);
$('#hfoValue').val(theVal);
//alert('copied');
}
</script>
<asp:DropDownList ID="ddlAddOptionValue" runat="server" ClientIDMode="Static" DataSourceID="OptionValues_DS"
DataTextField="Name" DataValueField="OptionValueID" AppendDataBoundItems="true"
SelectedValue='<%# Bind("OptionValueID") %>'>
<asp:ListItem Value="" Text="Select One..." />
</asp:DropDownList> ...
Finally access the value from the HiddenField:
protected void OptionSetValues_DS_Inserting(object sender, ObjectDataSourceMethodEventArgs e)
{
// if the value doesn't already exist, create it
if (e.InputParameters["OptionValueID"] == null)
{
// !!!! FOUND THE VALUE :)
string ovName = ((HiddenField)frmCreateOptionValue.FindControl("hfoValue")).Value;
int ovOptionID = Convert.ToInt32(Request.QueryString["OptionSetID"]);
tblOptionValueTableAdapter t = new tblOptionValueTableAdapter();
int ovID = Convert.ToInt32(t.InsertQuery(ovOptionID, ovName, 0, ""));
e.InputParameters["OptionValueID"] = ovID;
}
}
Thanks to #Miroprocessor for helping to solve this one

Resources