Get HTML dynamic input value ASP.NET - 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

Related

multilingual data from resource file

I have two resource file Resource.resx and Resource.ar.resx
with the same keys but different english and arabic data
in the following code the text in the is working fine showing english and arabic data with the change in the dropdownlist while the text of the save button always shows English not arabic
</tr>
<tr>
<td><span><%=Resources.Resource.Citations%></span></td>
<td>
<input runat="server" id="taCitations" type="number" style="width: 600px;" /></td>
</tr>
</table>
<asp:Button ID="btnSave" runat="server" Text="<%$Resources:Resource, Save%>" CssClass="btn" OnClick="btnSave_Click" />
I have a dropdownlist in master page
<asp:DropDownList ID="ddlLang" runat="server" AutoPostBack="true">
<asp:ListItem Text="English" Value="en-US">
<asp:ListItem Text="Arabic" Value="ar-sa" />
</asp:DropDownList>
and my work to change language is in preRender of the master page
protected void Page_PreRender(object sender, EventArgs e)
{
if (Request.Form["__EVENTTARGET"] != null && Request.Form["__EVENTTARGET"].Contains("ddlLang"))
{
//Set the Language.
Language = Request.Form[Request.Form["__EVENTTARGET"]];
}
if (Language == "en-US")
{
Body.Attributes["dir"] = "ltr";
tdAppParticulars.Attributes["align"] = "right";
}
else
{
Body.Attributes["dir"] = "rtl";
tdAppParticulars.Attributes["align"] = "left";
}
Thread.CurrentThread.CurrentCulture = new CultureInfo(Language);
Thread.CurrentThread.CurrentUICulture = new CultureInfo(Language);
List<ExtFormInstruction1> lefi = bal.ExtFormInstructionByType("External Reviewers");
formInstructions = new Hashtable();
formIDs = new Hashtable();
string currentItemURL = "";
foreach (ExtFormInstruction1 row in lefi)
{
string itemURL = row.Page;
formInstructions[row.Page] = Language == "ar-sa" ? "" : row.Instruction;
formIDs[row.Page] = row.FormID;
if (Language == "en-US")
{
lblPageTitle.Text = row.Title;
}
else if (Language == "ar-sa")
{
lblPageTitle.Text = bal.GetFormByPage(row.Page.Replace(".aspx", "Ar.aspx"))[0].Title;
}
}
MakeMenu(Language);
if (IsPostBack)
{
return;
}
lblApplicantEmail.Text = bal.GetApplicant(ApplicationID)[0].NameString;
lblEmployee.Text = erBAL.GetExtRevByID(ExtReviewerID)[0].Name;
/* printer friendly */
if (Utils.IsPrintMode())
{
tdLeftMenu.Visible = false;
lnkPrint.Visible = false;
}
lnkPrint.NavigateUrl = currentItemURL + "?print=1";
}
the Language is a property in master page
public string Language
{
set
{
Session["Language"] = value;
}
get
{
if (Session["Language"] != null)
{
return Session["Language"].ToString();
}
else
{
return "en-US";
}
}
}
I would rather do it like this:
<asp:Button ID="btnSave" runat="server" meta:resourceKey="SaveButton" CssClass="btn" OnClick="btnSave_Click" />
And in the Resource.resx file, the entries will be like
Name: SaveButton.Text
Value: Save
Name: SaveButton.Tooltip
Value: Click to Submit
Similarly in Resource.ar.resx file
Name: SaveButton.Text
Value: حفظ
Name: SaveButton.Tooltip
Value: انقر فوق لتقديم

how to write the java script for checked check boxes which is in item template of radcombobox

Actually in my radcombobox i am taking one template in that template i am taking three controls checkbox and linkbutton and imagebutton.i am binding the usernnames to linkbutton. and through itemcommand event of radcombobox i am displaying status in place of image every thing is working fine but my problem is when i check the check box of two users out of five users in combobox while closing radcombobox i want the names of the selected users in combobox by separated with coma(,) is it possible
below is my code
<telerik:RadComboBox ID="rdPhysicianscmb" runat="server" Width="75%"
DataSourceID="sdsAttachedUsers" Filter="Contains" Font-Size="14pt"
onitemdatabound="rdPhysicianscmb_ItemDataBound"
OnClientDropDownClosed="HandleClose" LoadingMessage="Loading..."
EmptyMessage="All Providers">
<ItemTemplate>
<asp:CheckBox ID="chk" Width="10px" runat="server"/>
<asp:Image Visible="false" ID="ImgAway" runat="server"
ImageUrl='images/imgAway.png' Style="height: 25px; width: 25px;"/>
<asp:LinkButton ID="lblphyname" runat="server" CommandName="Selected"
ForeColor="#0489B5" Font-Size="11pt"
CommandArgument='<%# Eval("AssignedTo") %>' onclick="lblphyname_Click"
Text='<%# Eval("FullName") %>' Font-Underline="false"
Font-Overline="false">
</asp:LinkButton>
</ItemTemplate>
</telerik:RadComboBox>
Please try with the below code snippet.
.ASPX
<telerik:RadComboBox ID="ddlEducationPeriod" runat="server" EmptyMessage="--Select education period--"
HighlightTemplatedItems="true" SkinID="DropDownList194*200" AllowCustomText="true">
<HeaderTemplate>
<asp:CheckBox ID="chkSelectAll" runat="server" onClick="EducationHeaderCheckChanged();" />
<asp:Label runat="server" ID="lblTeacherSelectAll" Text="Select All" AssociatedControlID="chkSelectAll"></asp:Label>
</HeaderTemplate>
<ItemTemplate>
<div onclick="StopPropagation(event)">
<asp:CheckBox runat="server" ID="chkddlID" onclick="onCheckBoxClickEducation(this)"
Text='<%#Eval("Name") %>' />
<asp:Label runat="server" ID="labelddlID" Text='<%#Eval("ID") %>' Visible="false"></asp:Label>
</div>
</ItemTemplate>
</telerik:RadComboBox>
.ASPX.CS
protected void Page_Load(object sender, EventArgs e)
{
dynamic data = new[] {
new { ID = 1, Name ="aaa"},
new { ID = 2, Name = "bbb"},
new { ID = 3, Name = "ccc"},
new { ID = 4, Name = "ddd"},
new { ID = 5, Name ="eee"},
new { ID = 6, Name ="aaa"},
new { ID = 7, Name = "bbb"},
new { ID = 8, Name = "ccc"},
new { ID = 9, Name = "ddd"},
new { ID = 10, Name ="eee"}
};
ddlEducationPeriod.DataSource = data;
ddlEducationPeriod.DataTextField = "Name";
ddlEducationPeriod.DataValueField = "ID";
ddlEducationPeriod.DataBind();
}
JAVASCRIPT
function onCheckBoxClickEducation(chk) {
var combo = $find("<%= ddlEducationPeriod.ClientID %>");
//prevent second combo from closing
cancelDropDownClosing = true;
//holds the text of all checked items
var text = "";
//holds the values of all checked items
var values = "";
//get the collection of all items
var items = combo.get_items();
//enumerate all items
for (var i = 0; i < items.get_count(); i++) {
var item = items.getItem(i);
//get the checkbox element of the current item
var chk1 = $get(combo.get_id() + "_i" + i + "_chkddlID");
if (chk1.checked) {
text += item.get_text() + ", ";
values += item.get_value() + ",";
}
}
//remove the last comma from the string
text = removeLastComma(text);
values = removeLastComma(values);
if (text.length > 0) {
//set the text of the combobox
combo.set_text(text);
//update the treeview in the second combobox
}
else {
//all checkboxes are unchecked
//so reset the controls
combo.set_text("");
}
}
function StopPropagation(e) {
e.cancelBubble = true;
if (e.stopPropagation) {
e.stopPropagation();
}
}
function EducationHeaderCheckChanged() {
var headerchk = document.getElementById('ddlEducationPeriod_Header_chkSelectAll');
onCheckBoxClickSelectAll(headerchk.checked, "ddlEducationPeriod");
}
function onCheckBoxClickSelectAll(headerchk, combo) {
var combo = $find("<%= ddlEducationPeriod.ClientID %>");
cancelDropDownClosing = true;
//holds the text of all checked items
var text = "";
//holds the values of all checked items
var values = "";
//get the collection of all items
//enumerate all items
var items = combo.get_items();
for (var i = 0; i < items.get_count(); i++) {
var item = items.getItem(i);
//get the checkbox element of the current item
var chk1 = $get(combo.get_id() + "_i" + i + "_chkddlID");
chk1.checked = headerchk;
if (chk1.checked) {
text += item.get_text() + ", ";
values += item.get_value() + ",";
}
}
//remove the last comma from the string
text = removeLastComma(text);
values = removeLastComma(values);
if (text.length > 0) {
//set the text of the combobox
combo.set_text(text);
}
else {
//all checkboxes are unchecked
//so reset the controls
combo.set_text("");
}
}
function removeLastComma(str) {
return str.slice(0, -2);
}

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>

Async/partial postback datagrid issues

I'm trying to get an aspx datagrid control to perform a post that results in a partial postback (asynchronous) rather than a full postback. I've added scriptmanager, an update panel, and a content template wrapper and yet it still refreshes the page when i select a data item and click add.
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePartialRendering="True" ></asp:ScriptManager>
<asp:UpdatePanel ID="upPnlLookup" runat="server" UpdateMode="Conditional" ChildrenAsTriggers="True">
<ContentTemplate>
<asp:DataGrid ID="ObjectPropertiesDataGrid" CellPadding="5" CellSpacing="5" OnItemCommand="ObjectPropertiesDataGrid_ItemCommand" OnItemDataBound="ObjectPropertiesDataGrid_ItemDataBound" AutoGenerateColumns="False" CssClass="List" DataKeyField="id" runat="server">
<asp:TemplateColumn>
<ItemTemplate>
<asp:Panel ID="multiValuePanel" Visible="false" runat="server">
<table>
<tr>
<td valign="top">
<asp:Button ID="addButton" CssClass="button" CommandName="AddValue" Width="65px" Text="Add" runat="server"></asp:Button>
<asp:Button ID="addAllButton" CssClass="button" CommandName="AddAllValue" Width="85px" Text="Add All" runat="server"></asp:Button>
<br />
<asp:ListBox ID="listBoxValues" Width="250px" CssClass="listbox" SelectionMode="Multiple" runat="server"></asp:ListBox>
</td>
<td valign="top">
<asp:Button ID="removeButton" CssClass="button" Text="Remove" Width="65px" CommandName="RemoveValue" runat="server"></asp:Button>
<asp:Button ID="removeAllButton" CssClass="button" Text="Remove All" Width="85px" CommandName="RemoveAllValue" runat="server"></asp:Button>
<br />
<asp:ListBox ID="listBoxCurrentValues" Width="250px" CssClass="listbox" SelectionMode="Multiple" runat="server"></asp:ListBox>
</td>
</tr>
</table>
</asp:Panel>
</ItemTemplate>
</asp:TemplateColumn>
</asp:DataGrid>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="addButton" EventName="Click" />
<asp:AsyncPostBackTrigger ControlID="removeButton" EventName="Click" />
<asp:AsyncPostBackTrigger ControlID="addAllButton" EventName="Click" />
<asp:AsyncPostBackTrigger ControlID="removeAllButton" EventName="Click" />
</Triggers>
</asp:UpdatePanel>
Code Behind (snippets/relevant methods):
protected void Page_Load(object sender, EventArgs e)
{
SaveButton.Click += SaveButton_Click;
btnAddChild.Click += btnAddChild_Click;
btnAddChildTop.Click += btnAddChildTop_Click;
DeleteButton.Click += DeleteButton_Click;
CancelButton.Click += CancelButton_Click;
CopyButton.Click += CopyButton_Click;
NewButton.Click += NewButton_Click;
AddSiteButton.Click += AddSiteButton_Click;
RemoveSiteButton.Click += RemoveSiteButton_Click;
ActivateAll.Click += ActivateAll_Click;
DeactivateAll.Click += DeactivateAll_Click;
startDateCalender.SelectionChanged += startDateCalender_SelectionChanged;
endDateCalender.SelectionChanged += endDateCalender_SelectionChanged;
startDateCalender.Load += startDateCalender_Load;
endDateCalender.Load += endDateCalender_Load;
CacheButton.Click += CacheButton_Click;
if (IsPostBack)
return;
if (String.IsNullOrEmpty(Request["id"]))
{
Response.Redirect("default.aspx");
}
else
{
LoadData();
}
}
private void LoadData()
{
Properties = ContentProviderFactory.GetContentProvider().GetObjectTypeProperties(CurrentContentObject.Type, false);
uploadImage.DataSource = DataHelper.GetObjecTypeImageSizes(CurrentContentObject.Type);
uploadImage.Container = CurrentContentObject;
foreach (var property in from Property p in Properties
let objectProperty = CurrentContentObject.GetProperty(p.Id)
where objectProperty == null
select p)
{
CurrentContentObject.Items.Add(property);
}
ObjectPropertiesDataGrid.DataSource = Properties;
var children = ContentProviderFactory.GetContentProvider().GetContentObjectChildren(CurrentContentObject.Id);
dgObjectChildren.DataSource = children.Where(c => c.Active);
dgObjectInactiveChildren.DataSource = children.Where(c => !c.Active);
dgObjectParents.DataSource = ContentProviderFactory.GetContentProvider().GetContentObjectParents(CurrentContentObject);
ddlContentTypes.DataSource = ContentProviderFactory.GetContentProvider().GetContentObjectTypes(CurrentContentObject.Type);
ddlContentTypesTop.DataSource = ContentProviderFactory.GetContentProvider().GetContentObjectTypes(CurrentContentObject.Type);
SitesListBox.DataSource = ContentProviderFactory.GetContentProvider().GetContentObjectSitesAvailable(CurrentContentObject.Id);
SetSitesListBox.DataSource = ContentProviderFactory.GetContentProvider().GetContentObjectSites(CurrentContentObject.Id);
if (CurrentContentObject.Id == 0)
{
Response.Status = "301 Moved Permanently";
Response.AddHeader("Location", "/admin/Contentobjects/ObjectNotFound.aspx");
Response.End();
}
const string DATE_FORMAT = "MM/dd/yyyy";
if (CurrentContentObject.StartDate.ToString(DATE_FORMAT) != SqlDateTime.MinValue.Value.ToString(DATE_FORMAT))
{
startDateTextBox.Text = CurrentContentObject.StartDate.ToShortDateString();
}
if (CurrentContentObject.EndDate.ToString(DATE_FORMAT) != SqlDateTime.MaxValue.Value.ToString(DATE_FORMAT))
{
endDateTextBox.Text = CurrentContentObject.EndDate.Date.ToShortDateString();
}
DataBind();
//if its an orphan child/child, remove 'add child' button and pulldown
if (ddlContentTypes.Items.Count == 0)
{
btnAddChild.Visible = false;
ddlContentTypes.Visible = false;
}
if (ddlContentTypesTop.Items.Count == 0)
{
ddlContentTypesTop.Visible = false;
btnAddChildTop.Visible = false;
}
// Add delete confirmation javascript
DeleteButton.Attributes["onclick"] = "return confirm_object_delete();";
RenderTypeHeader();
RenderBreadcrumb();
if (CurrentContentObject.ParentId == 0)
{
UserInfo.AddToHistory(CurrentContentObject.Id, CurrentContentObject.Name);
}
else
{
UserInfo.AddToHistory(CurrentContentObject.Parent.Id, CurrentContentObject.Parent.Name);
}
startCalenderPanel.Visible = false;
endCalenderPanel.Visible = false;
}
protected void ObjectPropertiesDataGrid_ItemCommand(object sender, DataGridCommandEventArgs e)
{
var id = (int)ObjectPropertiesDataGrid.DataKeys[e.Item.ItemIndex];
switch (e.CommandName.ToLower())
{
case "clearimage":
{
// Delete the image (does not physically remove the image but will be replaced if new a new one updates)
var imageProperty = e.Item.FindControl("imageProperty") as Image;
var tbFileName = e.Item.FindControl("tbFileName") as TextBox;
tbFileName.Text = string.Empty;
imageProperty.ImageUrl = string.Empty;
break;
}
case "addvalue":
{
// Adds a property value to the list of properites
var listBoxValues = e.Item.FindControl("listBoxValues") as ListBox;
var listBoxCurrentValues = e.Item.FindControl("listBoxCurrentValues") as ListBox;
foreach(var item in listBoxValues.Items.Cast<ListItem>().Where(item => item.Selected))
{
// Add item to the set values
listBoxCurrentValues.Items.Add(item);
}
for (var i = listBoxValues.Items.Count - 1; i >= 0; i--)
{
if (listBoxCurrentValues.Items.FindByValue(listBoxValues.Items[i].Value) != null)
{
listBoxValues.Items.RemoveAt(i);
}
}
SortListBox(listBoxCurrentValues);
break;
}
case "removevalue":
{
var listBoxValues = e.Item.FindControl("listBoxValues") as ListBox;
var listBoxCurrentValues = e.Item.FindControl("listBoxCurrentValues") as ListBox;
for(var i = listBoxCurrentValues.Items.Count - 1; i >= 0; i--)
{
if(listBoxCurrentValues.Items[i].Selected)
{
listBoxValues.Items.Add(listBoxCurrentValues.Items[i]);
listBoxCurrentValues.Items.RemoveAt(i);
}
}
SortListBox(listBoxValues);
break;
}
case "addallvalue":
{
var listBoxValues = e.Item.FindControl("listBoxValues") as ListBox;
var listBoxCurrentValues = e.Item.FindControl("listBoxCurrentValues") as ListBox;
foreach(ListItem item in listBoxValues.Items)
{
// Add item to the set values
listBoxCurrentValues.Items.Add(item);
}
for(var i = listBoxValues.Items.Count - 1; i >= 0; i--)
{
if(listBoxCurrentValues.Items.FindByValue(listBoxValues.Items[i].Value) != null)
{
listBoxValues.Items.RemoveAt(i);
}
}
SortListBox(listBoxCurrentValues);
break;
}
case "removeallvalue":
{
var listBoxValues = e.Item.FindControl("listBoxValues") as ListBox;
var listBoxCurrentValues = e.Item.FindControl("listBoxCurrentValues") as ListBox;
for (var i = listBoxCurrentValues.Items.Count - 1; i >= 0; i--)
{
listBoxValues.Items.Add(listBoxCurrentValues.Items[i]);
listBoxCurrentValues.Items.RemoveAt(i);
}
SortListBox(listBoxValues);
break;
}
case "addalldatalistvalue":
{
var dataListValues = e.Item.FindControl("DataListValues") as DataList;
var dataListCurrentValues = e.Item.FindControl("CurrentDataListValues") as DataList;
foreach (DataListItem item in dataListValues.Items)
{
ImageLink imageLink = ImageLinks[id][item.ItemIndex];
CurrentImageLinks[id].Add(imageLink);
}
for (var i = dataListValues.Items.Count - 1; i >= 0; i--)
{
if (CurrentImageLinks[id].Contains(ImageLinks[id][i]))
{
ImageLinks[id].RemoveAt(i);
}
}
dataListValues.DataSource = ImageLinks[id];
dataListCurrentValues.DataSource = CurrentImageLinks[id];
dataListValues.DataBind();
dataListCurrentValues.DataBind();
break;
}
case "removealldatalistvalue":
{
var dataListValues = e.Item.FindControl("DataListValues") as DataList;
var dataListCurrentValues = e.Item.FindControl("CurrentDataListValues") as DataList;
for (var i = dataListCurrentValues.Items.Count - 1; i >= 0; i--)
{
ImageLinks[id].Add(CurrentImageLinks[id][i]);
CurrentImageLinks[id].RemoveAt(i);
}
dataListValues.DataSource = ImageLinks[id];
dataListCurrentValues.DataSource = CurrentImageLinks[id];
dataListValues.DataBind();
dataListCurrentValues.DataBind();
break;
}
}
}
I think you have a runtime error in Page_Load. for example if you have this wrong codes, your page will refresh instead of update:
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
Response.Redirect("WebForm1.aspx");
int.Parse("");
}
}
also try this :
Control me = FindControl(Request.Params.Get("__EVENTTARGET"));
if(FindControl(me!=addButton && me!=removeButton && me!=addAllButton && me!=removeAllButton)
{
if (IsPostBack)
return;
if (String.IsNullOrEmpty(Request["id"]))
{
Response.Redirect("default.aspx");
}
else
{
LoadData();
}
}

ASP.NET with jQueryUI: text box value is getting as null in Button click event

I have an ASP.NET page where I have a button When a user clicks on the button,I will check whether the user has logged in or not.If not logged in I will show a modal popup to login (using jQueryUI). I have placed one textbox(txtPassword) and one button(btnLogin) control in the Div which will be shown by the jQueryDialog.But in btnLogin's Click event, I am not able to read the Text value entered in the textbox txtPassword
The below is my code
<form id="form1" runat="server">
<div>
<br />
<asp:TextBox ID="txtModelId" runat="server" Text=""></asp:TextBox><br />
<asp:Button ID="btnGo" runat="server" Text="Go" OnClick="btnGo_Click" />
<br />
<asp:Label ID="lblUserMsg" runat="server" Text="Label"></asp:Label></div>
<div id="divContentHolder">
<div class="demo">
<div id="dialog" title="Login with your TradeIn Account">
<p id="validateTips">Enter your EmailId & password</p>
<fieldset>
<label for="email">Email</label>
<asp:TextBox ID="txtEmail" CssClass="text ui-widget-content ui-corner-all" runat="server" ></asp:TextBox>
<label for="password">
<asp:TextBox ID="TextBox1" runat="server" Text="sample"></asp:TextBox>Password</label>
<asp:TextBox ID="txtPassword" CssClass="text ui-widget-content ui-corner-all" runat="server" ></asp:TextBox>
<asp:Button ID="btnLogin" runat="server" Text="Login" OnClick="btnLogin_Click" UseSubmitBehavior="false"/>
</fieldset>
</div><!--dialog-->
</div><!--demo-->
</div><!--divContentHolder-->
</form>
Server side Code
protected void btnGo_Click(object sender, EventArgs e)
{
CheckUserLoggedIn();
}
private void CheckUserLoggedIn()
{
if (Session["username"] != null)
{
Response.Write("Logged in user");
ClientScript.RegisterHiddenField("isAuthenticated", "true");
}
else
{
ClientScript.RegisterHiddenField("isAuthenticated", "false");
}
}
protected void btnLogin_Click(object sender, EventArgs e)
{
string txtSample= TextBox1.Text; // this is showing the value 'sample'
string txtPass= txtPassword.Text; // this is showing null
if (txtPass == "shyju")
{
Session["username"] = txtPassword.Text;
Response.Redirect("TestingModal.aspx");
}
}
My java script code to render the dialog
$(function() {
var name = $("#name"),
email = $("#email"),
password = $("#password"),
allFields = $([]).add(name).add(email).add(password),
tips = $("#validateTips");
function updateTips(t) {
tips.text(t).effect("highlight",{},1500);
}
function checkLength(o,n,min,max) {
if ( o.val().length > max || o.val().length < min ) {
o.addClass('ui-state-error');
updateTips("Length of " + n + " must be between "+min+" and "+max+".");
return false;
} else {
return true;
}
}
function checkRegexp(o,regexp,n) {
if ( !( regexp.test( o.val() ) ) ) {
o.addClass('ui-state-error');
updateTips(n);
return false;
} else {
return true;
}
}
$("#dialog").dialog({
bgiframe: true,
autoOpen: false,
height: 300,
modal: true,
buttons: {
'Create an account': function() {
var bValid = true;
allFields.removeClass('ui-state-error');
bValid=true;
if (bValid) {
/*$('#users tbody').append('<tr>' +
'<td>' + name.val() + '</td>' +
'<td>' + email.val() + '</td>' +
'<td>' + password.val() + '</td>' +
'</tr>'); */
alert("Check User Credentials")
$(this).dialog('close');
}
},
Cancel: function() {
$(this).dialog('close');
}
},
close: function() {
allFields.val('').removeClass('ui-state-error');
}
});
$('#create-user').click(function() {
$('#dialog').dialog('open');
})
.hover(
function(){
$(this).addClass("ui-state-hover");
},
function(){
$(this).removeClass("ui-state-hover");
}
).mousedown(function(){
$(this).addClass("ui-state-active");
})
.mouseup(function(){
$(this).removeClass("ui-state-active");
});
var isAuthenticated = $("#isAuthenticated").val();
if (isAuthenticated && isAuthenticated == "false")
{
// Display the modal dialog.
$("#dialog").dialog("open");
}
});
I had hard coded the text properties value of TextBox1 as 'sample' in the HTML part of my ASPX file .In button click event i am getting it.But the other textbox,txtPassword 's Text property is giving me null value
Please guide me to go ahead
Thanks in advance
Try to get txtPassword value like this
string val=txtPassword.Attributes["value"].ToString();

Resources