Address bar is showing the address of previous page - c#

I am having Default.aspx Page for Login. After Successful Login it shows the ItemValuation.aspx Page but in the address bar the link shown is Default.aspx. The problem started after I implimented the jquery in my Project. If I remove the jquery
references and Code then link shown is correct after login i.e. ItemValuation.aspx
Can any one tell me how can I solve this Problem? After successful Login on Default.aspx the link shown in address bar should be ItemValuation.aspx For your reference I am posting the Default Page aspx code.
Thanks in Advance.
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="Item_Valuation.Default" %>
<!DOCTYPE html >
<html >
<head runat="server">
<link rel="shortcut icon" href="~/Images/ACME.ico">
<title>Login</title>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0;"/>
<link href="css/jquery.mobile-1.1.0.min.css" rel="stylesheet" type="text/css" />
<link href="css/jquery-ui-1.8.18.custom_mini.css" rel="stylesheet" type="text/css" />
<script src="js/jquery-1.7.1.min.js" type="text/javascript"></script>
<script src="js/jquery.mobile-1.1.0.min.js" type="text/javascript"></script>
</head>
<body >
<div data-role="page" id ="loginpage" data-theme="c" >
<form id="formLogin" runat="server" >
<div id ="DivHeader" data-role="header" data-position="fixed" data-theme="c" >
<div style="text-align:center;top:4px;">
<asp:Image ID="Image1" runat="server"
ImageUrl="Images/ItmVlun.jpg" />
</div>
</div>
<div data-role="content" style=" margin-top: 2px;">
<table style="text-align:right;width:100%">
<tr>
<td style="width:80%" >
<table style="border-color: #FFCC00;width:100%;left:5%; text-align:left;">
<tr>
<td style="width:50%;"><asp:Label ID="lblLogin" runat="server" Text="Login:"
Font-Bold="False" Font-Names="Copperplate Gothic Light" Font-Size="Large"></asp:Label>
</td>
<td style="width:50%;"><input id="txtUserName" type="text" runat="server" style="width:100%;font-size:large;" /></td>
<td><ASP:RequiredFieldValidator ControlToValidate="txtUserName"
Display="Static" ErrorMessage="*" runat="server"
ID="vUserName" /></td>
</tr>
<tr>
<td >
<asp:Label ID="lblPassword" runat="server" Text="Password:" Font-Bold="False"
Font-Names="Copperplate Gothic Light" Font-Size="Large"></asp:Label>
</td>
<td ><input id="txtUserPass" type="password" runat="server" style="width:100%;font-size:large;" /></td>
</tr>
<tr>
<td >
<asp:Label ID="lblRememberMe" runat="server" Text="Remember Me:"
Visible="False" Font-Names="Copperplate Gothic Light"></asp:Label>
</td>
<td >
<asp:CheckBox ID="chkPersistCookie" runat="server" autopostback="false"
Visible="False" />
</td>
<td ></td>
</tr>
</table>
</td>
<td style="width:20%;">
<asp:Image ImageAlign=Right ID="Image2" runat="server"
ImageUrl="~/Images/LogInimg.jpg" Width="100%" Height=60% />
</td>
</tr>
</table>
</div>
<div data-role="footer" data-position="fixed" data-theme="c">
<asp:Button ID="btnLogIn" runat="server" OnClick="LogMe_Click"
Text="Log in" data-theme="a" CausesValidation="False" data-role="button" data-inline="true" style=" float : left;" />
<input type="button" ID="CloseButton" value="Close" onclick ="window.close();" />
<asp:Label ID="lblMsg" runat="server" ForeColor="#FF0066" style=" float : Right;" ></asp:Label>
</div>
</form>
</div>
</body>
</html>
//Default.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
//using System.Web.UI.MobileControls;
using System.Runtime.InteropServices;
namespace Item_Valuation
{
public partial class Default : System.Web.UI.Page
{
// internal static extern int lineGetGeneralInfo(IntPtr hLine, byte[] bCache);
//public static string IMEI;
Item_Valuation.User usr;
public static string message="";
public string AuthorisationMsg;
protected void Page_Load(object sender, EventArgs e)
{
try
{
if (!IsPostBack)
{
if (Request.QueryString["TCPServer"] != null)
{
AuthorisationMsg = Request.QueryString["TCPServer"].ToString();
GlobalData.SetSettings();
lblMsg.Text = "Error: TCP Server IP " + GlobalData.TCPServer + " " + AuthorisationMsg;
}
else if (Request.QueryString["Message"] != null)
{
lblMsg.Text = Request.QueryString["Message"].ToString();
}
}
txtUserName.Focus();
}
catch (Exception ee)
{
lblMsg.Text = ee.Message;
}
}
private bool ValidateUser(string userName, string passWord)
{
if ((null == userName) || (0 == userName.Length))
{
return false;
}
try
{
string msg = "";
Item_Valuation.User Usr = Item_Valuation.User.CheckLogin(userName, passWord, ref msg);
if (msg.Length > 0)
{
lblMsg.Text = msg;
Response.Write("<script>'alert("+lblMsg.Text +"')</script>");
return false;
}
if (Usr != null)
{
}
else
{
lblMsg.Text = "Invalid Login id or Password";
Response.Write("<script>'alert(" + lblMsg.Text + "')</script>");
return false;
}
}
catch (Exception ex)
{
// AcmePayRollBusiness.PayRollError.PostError(this.GetType(), ex, "Error while validating User");
return false;
}
return true;
}
public void LogMe_Click(object sender, EventArgs e)
{
if (ValidateUser(txtUserName.Value, txtUserPass.Value))
{
FormsAuthenticationTicket tkt;
string cookiestr;
HttpCookie ck;
tkt = new FormsAuthenticationTicket(1, txtUserName.Value, DateTime.Now,
DateTime.Now.AddMinutes(30), chkPersistCookie.Checked, "your custom data");
cookiestr = FormsAuthentication.Encrypt(tkt);
ck = new HttpCookie(FormsAuthentication.FormsCookieName, cookiestr);
if (chkPersistCookie.Checked)
ck.Expires = tkt.Expiration;
ck.Path = FormsAuthentication.FormsCookiePath;
Response.Cookies.Add(ck);
string strRedirect=null;
//strRedirect = Request["ReturnUrl"];
usr = (Item_Valuation.User)HttpContext.Current.Session["User"];
int roleLevel = usr.RoleLevel;
if (roleLevel != 1)
{
if (strRedirect == null)
strRedirect = "ItemValuation.aspx";
}
else
{
if (strRedirect == null)
strRedirect ="PrinterAssignment.aspx";
}
Response.Redirect(strRedirect);
//Server.Transfer(strRedirect);
}
}
}
}

jQuery Mobile is the one that's doing that. By default, it changes all links and form submissions through AJAX.
To disable this... interesting... functionality, you need to add a handler to the mobileinit event, and set ajaxEnabled to false.
Docs here on how exactly to do this: http://jquerymobile.com/demos/1.1.0/docs/api/globalconfig.html

Related

ASP.NET passing a function return value from a modalpopupextender to the main form

I have looked at a number of solutions to my basic issue, but have not found any solution that I either understand or that would work.
I have a page that takes in two items of information, filename and a store. The user then clicks on a button to execute a function that will update a database and send back a resulting string that I want to display on a textbox on the main form.
However, when they press the button I call a modalpopupextender using an UpdatePanel panel. That gets a value into the modalpopup. If the user validates that the correct store is selected they click an 'okay' button which then call the dbprocessing function that returns a result. The page is small so I'll give the complete aspx and c# code.
The function doProcess() returns a List of values which I convert to String for display. I left the session variables in for that was my last attempt at trying to get this to work.
Where I am confused is that when the first button on the main form (Process) is clicked, there is a postback which obviously hits the page load before the button click. That is when I display the popup. Then when the user clicks on the button Okay, another postback is perform hitting page load before the button click and in that second button I originally tried to set the textbox on the main page because there is no other action after the second click, but no data displayed.
What is strange, if I repeat the process, when I click to display the popup, my data displays. This is not making sense.
This is the aspx page
<%# Page Title="Product Rank Loader" Language="C#" MasterPageFile="~/OMnested.master" AutoEventWireup="true" CodeBehind="ProductRankLoader.aspx.cs" Inherits="OrderManager.ProductRankLoader" %>
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajax" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<script type="text/javascript" src="Scripts/jquery-1.7.1.min.js"></script>
<script type="text/javascript" src="Scripts/local.js"></script>
<script type="text/javascript">
function callme(thisone)
{
$("#ddlStores").prop('disabled', false);
}
</script>
<div>
<table style="width: 500px">
<tr>
<td>
<asp:Label ID="lblMessage" runat="server"></asp:Label>
</td>
</tr>
<tr>
<td>
<asp:FileUpload ID="fulRanks" runat="server" Width="315px" />
</td>
</tr>
<tr>
<td>
<asp:DropDownList ID="ddlStores" runat="server" Height="16px" Width="155px">
<asp:ListItem Value="0">Select Store</asp:ListItem>
<asp:ListItem Value="10101">Parkseed</asp:ListItem>
<asp:ListItem Value="10151">Wayside</asp:ListItem>
<asp:ListItem Value="10201">Jackson (JP)</asp:ListItem>
</asp:DropDownList>
</td>
</tr>
<tr>
<td style="height: 20px; padding-top: 15px; padding-bottom: 15px; padding-left: 20px;">
<asp:Button ID="btnProcess" runat="server" Text="Process" Width="89px" OnClick="btnProcess_Click" />
</td>
</tr>
<tr>
<td>
**<asp:TextBox ID="txtResults" runat="server" Height="200px" ReadOnly="True" TextMode="MultiLine"></asp:TextBox>**
</td>
</tr>
</table>
<asp:HiddenField ID="hdnFilename" runat="server" />
</div>
<asp:UpdatePanel id="updVerifyChoice" runat="server">
<ContentTemplate>
<div style="display: none;">
<asp:Button ID="btnDummy" UseSubmitBehavior="true" OnClientClick="ShowModalPopup" OnClick="btnDummy_Click" runat="server" />
<%--Dummy Button added to assign the target controlid of PopupExtender--%>
<asp:Button ID="btnDummyButton" UseSubmitBehavior="true" runat="server" Text="DummyButton" Style="display: none;" />
</div>
<asp:Panel ID="pnlVerifyRequestPopup" runat="server">
<div style="background: #fff; padding-left: 3px; border: 1px solid #989898; border-top: 1px solid #989898 !important;">
<table style="background-color: #F7F5F4; width: 300px;">
<tr>
<td><label>Verify Process Request</label></td>
<td style="text-align: right;">
<label class="lbl_3">
<asp:LinkButton ID="lBtnVerifyRequestClose" CssClass="lnkCloseheaderedit" Text="Cancel"
runat="server" OnClick="lBtnBillUpdPopClose_Click" /></label>
</td>
</tr>
<tr>
<td style="width: 150px;" colspan="2">
<asp:Label ID="lblWarn" runat="server" Text="" Font-Size="Medium" ForeColor="#CC3300"></asp:Label>
</td>
</tr>
<tr>
<td colspan="2" class="align_right">
<asp:Button ID="btnPopVerify" runat="server" CssClass="order_searchbtn" Text="Okay"
OnClick="btnPopVerify_Click" />
</td>
</tr>
</table>
<asp:HiddenField ID="hdnReturnData" runat="server" />
</div>
</asp:Panel>
<ajax:ModalPopupExtender ID="extVerifyProcess" runat="server" BehaviorID="extndPopBillUpdBehId"
TargetControlID="btnDummyButton" PopupControlID="pnlVerifyRequestPopup" CancelControlID="lBtnVerifyRequestClose">
</ajax:ModalPopupExtender>
</ContentTemplate>
</asp:UpdatePanel>
</asp:Content>
The field in question that should get the returned values from the function is called txtResults.
Here is the c# code (I cut out unneeded code)
namespace OrderManager
{
public partial class ProductRankLoader : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
var currentUser = Request.LogonUserIdentity.Name.Split('\\')[1];
// Session.Add("returnText", "");
var header = Master.FindControl("lblpageheading") as Label;
header.Text = "Product Rank Loader";
if (IsPostBack)
{
try
{
//if (Session["Verified"].ToString() != "")
//{
Session["returnText"] = doProcess();
if (Session["returnText"].ToString() != "")
{
txtResults.Text = Session["returnText"].ToString();
lblMessage.Text = "";
}
//}
}
catch { }
} else
{
Session.Add("returnText", "");
Session.Add("Verified", "");
}
}
protected void btnProcess_Click(object sender, EventArgs e)
{
Boolean fileOK = false;
string filename = Path.GetFileName(fulRanks.FileName);
hdnFilename.Value = filename;
if (fulRanks.HasFile)
{
ddlStores.Enabled = true;
String fileExtension =
System.IO.Path.GetExtension(fulRanks.FileName).ToLower();
String[] allowedExtensions = { ".txt", ".log" };
for (int i = 0; i < allowedExtensions.Length; i++)
{
if (fileExtension == allowedExtensions[i])
{
fileOK = true;
fulRanks.SaveAs(#"c:\temp\" + filename);
}
}
}
if (!fileOK || ddlStores.SelectedIndex <= 0)
{
lblMessage.Text = "Either the file name is incorrect or a store has not been selected.";
return;
} else { }
lblWarn.Text = "You are going to update item Ranks for store <br />" + ddlStores.SelectedItem + ".<br /><br />Press 'Okay' to process";
Session.Add("Verified", "true");
extVerifyProcess.Show();
}
protected void lBtnBillUpdPopClose_Click(object sender, EventArgs e)
{
Session["Verified"] = "";
Session["returnText"] = "";
Response.Redirect("ProductRankLoader.aspx");
}
protected void btnPopVerify_Click(object sender, EventArgs e)
{
//Session["returnText"] = doProcess();
Session.Remove("returnText");
Session.Remove("Verified");
}
private string doProcess()
{
string tmpResults = "";
Int32 store = 0;
if (ddlStores.SelectedIndex > 0)
{
Int32.TryParse(ddlStores.SelectedValue.ToString(), out store);
string filename = hdnFilename.Value;
ProductRankLoaderDLL.ProductRankLoaderDLL newRanks = new ProductRankLoaderDLL.ProductRankLoaderDLL(xxx);
List<string> results = newRanks.ProcessRanks();
foreach (string result in results)
{
tmpResults += result + '\r';
}
// txtResults.Text = tmpResults;
lblMessage.Text = "";
}
else
{
lblMessage.Text = "";
}
return tmpResults;
}
protected void btnDummy_Click(object sender, EventArgs e)
{
}
}
}
If I don't misunderstand your request your problem is caused by the postbacks. I think you can handle better your logic with jquery. For example you can use jquery to close the popup without performing postback:
$('#lBtnVerifyRequestClose').click(function (event) {
event.preventDefault();
$('#pnlVerifyRequestPopup').dialog('close');
});
the event.preventDefault() ensure that postback are not executed.
If you need server logic to put data on your popup you can bind a jquery function to the dialog on open event and retrieve there data / perform your logic. In this way your form will be submitted to the server only once at the end of the process.

How to view image in image box just after the user has selected an image in file upload in code behind in asp.net

My html code is this
<asp:Image ID="Img_CreateUser" runat="server"/>
<asp:FileUpload ID="Upload_CreateUser" runat="server" />
My C# code is this
byte[] ImgArr = null;
if(Upload_CreateUser.PostedFile != null)
{
HttpPostedFile File = (HttpPostedFile)Upload_CreateUser.PostedFile;
string Filename = Path.GetFileName(Upload_CreateUser.FileName);
Upload_CreateUser.SaveAs(Server.MapPath("~/") + Filename);
//byte[] filebytes = Upload_CreateUser.FileBytes;
using(FileStream filestream = new FileStream(Filename, FileMode.Open, FileAccess.Read))
{
ImgArr = new byte[filestream.Length];
int ImgReadArr = filestream.Read(ImgArr, 0, (int)filestream.Length);
if(ImgArr != null && ImgArr.Length > 0)
{
string ImgType = File.ContentType;
string base64string = Convert.ToBase64String(ImgArr, 0, ImgArr.Length);
Img_CreateUser.ImageUrl = "data:" +ImgType+ ";base64," + base64string;
}
`
I dont want to save my image into database. I just want to preview it.
Thanks
Use following code
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Preview Image While Upload</title>
<script src="jquery-1.8.2.js" type="text/javascript"></script>
<script type="text/javascript">
function ShowPreview(input) {
if (input.files && input.files[0]) {
var ImageDir = new FileReader();
ImageDir.onload = function(e) {
$('#impPrev').attr('src', e.target.result);
}
ImageDir.readAsDataURL(input.files[0]);
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<table cellpadding="10" cellspacing="4" width="70%" align="center" style="border: Solid 10px Green;
font-weight: bold; font-size: 16pt; background-color: Skyblue; color: Blue;">
<tr>
<td align="center">
Upload Images
</td>
</tr>
<tr>
<td>
Select Your File To Upload #:
<input type="file" name="ImageUpload" id="ImageUpload" onchange="ShowPreview(this)" />
<asp:Button ID="btnUpload" runat="server" Text="Upload" />
</td>
</tr>
<tr>
<td>
<asp:Image ID="impPrev" runat="server" Height="200px" />
</td>
</tr>
</table>
</form>
</body>
</html>
For more details Go through the link it will help you
Preview Image Before Uploading
<script type="text/javascript">
function previewFile() {
var preview = document.querySelector('#<%=ImgPropertyGroupImageAdd.ClientID %>');
var file = document.querySelector('#<%=InputPropertyGroupImageAdd.ClientID %>').files[0];
var reader = new FileReader();
reader.onloadend = function () {
preview.src = reader.result;
}
if (file) {
reader.readAsDataURL(file);
} else {
preview.src = "";
}
}
</script>
<asp:Image ID="ImgPropertyGroupImageAdd" runat="server" Width="200px" Height="200px" ImageUrl="~/Images/Open.png" />
<asp:FileUpload ID="InputPropertyGroupImageAdd" type="file" onchange="previewFile()" runat="server" />

Why is my smtp SendMail prohibiting Log in fuctions, on site master?

I'm working in asp.net with c# and I decided to build a pop-up messaging module. I have done this on previous projects; however, I've never used it on a site that was also utilizing the Identity Framework or placed in my master page. I am also fairly new to C#.
The messenger appears to be working fine. However, now any kind of "submit" or "send" function found on the master page will not work properly. For example, if I try to log in as an admin, I will get my windows error messages for the field validation on the messenger. I tried taking out the RequiredFieldValidators, I was still unable to log in, instead it tried to send a message.
I then tried moving the module into a usercontrol and running it that way, still no luck. I had considered building a new masterpage for the log in page, that way I could remove the "contact" from the navigation on that page, thus eliminating the issue . However, I would prefer not to have to do this. I am sure there is a simple solution to correcting this, and my lack of experience with c# is not helping much.
Here is part of the navigation on my Site.Master, just to give an idea about what I'm doing:
<li><a runat="server" href="#" data-toggle="modal" data-target=".pop-up-1">Contact</a></li>
</ul>
<asp:LoginView runat="server" ViewStateMode="Disabled">
<AnonymousTemplate>
<ul class="nav navbar-nav navbar-right">
<li><a runat="server" href="~/Account/Login" style="color:#f46de6">Admin</a></li>
<li><asp:HyperLink ID="PayPalViewCart" runat="server" NavigateUrl=<%# Link.ToPayPalViewCart() %> style="color:#f46de6">View Cart</asp:HyperLink></li>
</ul>
</AnonymousTemplate>
<LoggedInTemplate>
<ul class="nav navbar-nav navbar-right">
<li><a runat="server" href="~/Account/Manage" title="Manage your account" style="color:#f46de6" >Hello, Admin</a></li>
<li>
<asp:LoginStatus runat="server" LogoutAction="Redirect" LogoutText="Log off" LogoutPageUrl="~/" OnLoggingOut="Unnamed_LoggingOut" />
</li>
</ul>
</LoggedInTemplate>
</asp:LoginView>
</div>
</div>
</div>
<uc1:popup1 runat="server" id="popup1" />
<div class="container body-content">
Now here is the code behind on this page, site.Master.cs:
public partial class SiteMaster : MasterPage
{
private const string AntiXsrfTokenKey = "__AntiXsrfToken";
private const string AntiXsrfUserNameKey = "__AntiXsrfUserName";
private string _antiXsrfTokenValue;
protected void Page_Init(object sender, EventArgs e)
{
// The code below helps to protect against XSRF attacks
var requestCookie = Request.Cookies[AntiXsrfTokenKey];
Guid requestCookieGuidValue;
if (requestCookie != null && Guid.TryParse(requestCookie.Value, out requestCookieGuidValue))
{
// Use the Anti-XSRF token from the cookie
_antiXsrfTokenValue = requestCookie.Value;
Page.ViewStateUserKey = _antiXsrfTokenValue;
}
else
{
// Generate a new Anti-XSRF token and save to the cookie
_antiXsrfTokenValue = Guid.NewGuid().ToString("N");
Page.ViewStateUserKey = _antiXsrfTokenValue;
var responseCookie = new HttpCookie(AntiXsrfTokenKey)
{
HttpOnly = true,
Value = _antiXsrfTokenValue
};
if (FormsAuthentication.RequireSSL && Request.IsSecureConnection)
{
responseCookie.Secure = true;
}
Response.Cookies.Set(responseCookie);
}
Page.PreLoad += master_Page_PreLoad;
}
protected void master_Page_PreLoad(object sender, EventArgs e)
{
if (!IsPostBack)
{
// Set Anti-XSRF token
ViewState[AntiXsrfTokenKey] = Page.ViewStateUserKey;
ViewState[AntiXsrfUserNameKey] = Context.User.Identity.Name ?? String.Empty;
}
else
{
// Validate the Anti-XSRF token
if ((string)ViewState[AntiXsrfTokenKey] != _antiXsrfTokenValue
|| (string)ViewState[AntiXsrfUserNameKey] != (Context.User.Identity.Name ?? String.Empty))
{
throw new InvalidOperationException("Validation of Anti-XSRF token failed.");
}
}
}
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Unnamed_LoggingOut(object sender, LoginCancelEventArgs e)
{
Context.GetOwinContext().Authentication.SignOut();
}
}
}
This is my user control for the pop-up:
<div class="modal fade pop-up-1" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel-1" aria-hidden="true">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myLargeModalLabel-3">Contact Us</h4>
</div>
<div class="modal-body">
<table style="max-width:100%; height: auto; padding:20px">
<tr>
<td colspan="3">
<div style="margin:15px 0 20px 0"> Please, use the form below to contact us regarding any questions or concerns you might have:</div>
</td>
</tr>
<tr style="margin-bottom:10px">
<td style="width:150px; font-size:14px">Name:</td>
<td style="vertical-align:top; width:300px">
<asp:TextBox ID="txtName" runat="server" Width="300px" style="margin:10px"/>
</td>
<td>
<!--<asp:RequiredFieldValidator ID="rfvName" runat="server"
ControlToValidate="txtName" Display="Dynamic"
ErrorMessage="Name">*</asp:RequiredFieldValidator>-->
</td>
</tr>
<tr style="margin-bottom: 10px ">
<td style="font-size: 14px">Organization (optional):</td>
<td><asp:TextBox ID="txtOrganization" runat="server" Width="300px" style="margin:10px" /></td>
<td>
</td>
</tr>
<tr style="margin-bottom:10px">
<td style="font-size:14px"> Phone (optional):</td>
<td><asp:TextBox ID="txtPhone" runat="server" Width="300px" style="margin:10px" /></td>
<td>
</td>
</tr>
<tr style="margin-bottom:10px">
<td style="font-size:14px">Email:</td>
<td><asp:TextBox ID="txtEmail" runat="server" Width="300px" style="margin:10px" /></td>
<td>
<!--<asp:RequiredFieldValidator ID="rfvEmail" runat="server"
ControlToValidate="txtEmail" Display="Dynamic"
ErrorMessage="Email">*</asp:RequiredFieldValidator>-->
</td>
</tr>
<tr>
<td style="font-size:14px"> Message:</td>
<td><asp:TextBox ID="txtRequest" runat="server" TextMode="MultiLine" Width="300px" Height="60px" style="margin:10px" /></td>
<td>
<!--<asp:RequiredFieldValidator ID="rfvRequest" runat="server"
ControlToValidate="txtRequest" Display="Dynamic"
ErrorMessage="Message">*</asp:RequiredFieldValidator>-->
</td>
</tr>
<tr>
<td colspan="3">
<asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="SendMail" Width="60px" />
<asp:Button ID="btnReset" runat="server" Text="Reset" OnClick="ResetEmail" Width="60px" CausesValidation="false" />
<!--<asp:ValidationSummary ID="ValidationSummary1" runat="server" HeaderText="Please fill out the required fields:" ShowMessageBox="true" ShowSummary="false" />-->
</td>
</tr>
</table>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal Contact Table-->
And last but not least, this is the code behind on the user control, and yes I know I can do this using my web.config also, and I tried that too with the same result:
public partial class pop_up_1 : System.Web.UI.UserControl
{
private bool IsValid;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void SendMail(object sender, EventArgs e)
{
if (IsValid)
{
//create a new email message
MailMessage mail = new MailMessage();
mail.From = new MailAddress("");
mail.To.Add("");
mail.Subject = "Information Request";
mail.IsBodyHtml = true;
mail.Body = "Name:" + this.txtName.Text + "<br />";
mail.Body += "Organization:" + txtOrganization.Text + "<br />";
mail.Body += "Phone:" + txtPhone.Text + "<br />";
mail.Body += "Email:" + txtEmail.Text + "<br />";
mail.Body += "Request or Question:" + txtRequest.Text + "<br />";
//Create SMTP client
SmtpClient smtp = new SmtpClient();
smtp.Host = "";
//Send the email
smtp.Send(mail);
//Define the name and type of the client script on the page.
String csName = "SuccessNotificationScript";
Type csType = this.GetType();
//Get a ClientScriptManager reference from the Page class.
ClientScriptManager cs = Page.ClientScript;
//Check to see if the client script is already registered.
if (!cs.IsClientScriptBlockRegistered(csType, csName))
{
string csText = "<script language='javascript'>window.alert('Thank you for submitting your request');</script>";
cs.RegisterClientScriptBlock(csType, csName, csText.ToString());
}
//Clear the form
ClearForm();
}
}
protected void ResetEmail(object sender, EventArgs e)
{
ClearForm();
}
protected void ClearForm()
{
txtName.Text = "";
txtOrganization.Text = "";
txtPhone.Text = "";
txtEmail.Text = "";
txtRequest.Text = "";
}
}
}
Any suggestions or ideas, greatly appreciated. Thanks
here is the backend of my login page, I am using identity framework:
public partial class Login : Page
{
protected void Page_Load(object sender, EventArgs e)
{
//RegisterHyperLink.NavigateUrl = "Register";
// Enable this once you have account confirmation enabled for password reset functionality
// ForgotPasswordHyperLink.NavigateUrl = "Forgot";
//OpenAuthLogin.ReturnUrl = Request.QueryString["ReturnUrl"];
var returnUrl = HttpUtility.UrlEncode(Request.QueryString["ReturnUrl"]);
if (!String.IsNullOrEmpty(returnUrl))
{
//RegisterHyperLink.NavigateUrl += "?ReturnUrl=" + returnUrl;
}
}
protected void LogIn(object sender, EventArgs e)
{
if (IsValid)
{
// Validate the user password
var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>();
ApplicationUser user = manager.Find(Email.Text, Password.Text);
if (user != null)
{
IdentityHelper.SignIn(manager, user, RememberMe.Checked);
IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);
}
else
{
FailureText.Text = "Invalid username or password.";
ErrorMessage.Visible = true;
}
}
}
}
}

Disabled button refreshes

I Have an aspx page that contains 2 buttons "Update" and "Default". I have a dropdown list which contains a few values, say 1 to 10. When I click on Default button, the dropdown is set to a default value, say 4. If I wish to set the dropdown value to 3, I choose 3 and click on Update button and the changes are saved somewhere, maybe a DB.
Initially, Update button is disabled. Only if any changes are made to the dropdown, the Update button is enabled. Assuming that the Update button is initially disabled, I click the Default button to set the dropdown to its initial value. When I do that, a postback happens during which the Update button suddenly becomes enabled and then disabled. How do I avoid this? During page refresh, I don't want the disabled Update button to become enabled and then disabled. ALl this happens in a millisecond but its still visible.
is there any way out of this?
Design code is as follows:
ASPX
<%# Page Language="C#" AutoEventWireup="true" CodeFile="LogSettings.aspx.cs" Inherits="Settings_LogSettings" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Diagnostic Server Configuration Tool</title>
<link rel="stylesheet" type="text/css" href="../css/style001.css" />
<style type="text/css">
a.info
{
position: relative; /*this is the key*/
z-index: 24; /*background-color:#ccc;*/
color: #000;
border-width: 0px;
border-style: none;
text-decoration: none;
}
a.info:hover
{
z-index: 25;
background-color: #ff0;
}
a.info span
{
display: none;
}
a.info:hover span
{
/*the span will display just on :hover state*/
display: block;
position: absolute;
bottom: 2em;
right: 2em;
width: 15em;
border: 1px solid #0cf;
background-color: #cff;
color: #000;
text-align: left;
padding: 5px;
}
</style>
<script language="javascript" type="text/javascript">
function setDefaults() {
if (document.getElementById("dlLoggingLevel").value != document.getElementById("dlLoggingLevel_Def").value) {
document.getElementById("dlLoggingLevel").value = document.getElementById("dlLoggingLevel_Def").value;
document.getElementById("imgLoggingLevel").src = "../images/field_ok.png";
document.getElementById("imgLoggingLevelUndo").style.display = "inline";
document.getElementById("btnUpdate").disabled = false;
}
if (document.getElementById("txtMaxFileSize").value != document.getElementById("txtMaxFileSize_Def").value) {
document.getElementById("txtMaxFileSize").value = document.getElementById("txtMaxFileSize_Def").value;
document.getElementById("imgMaxSize").src = "../images/field_ok.png";
document.getElementById("imgMaxSizeUndo").style.display = "inline";
document.getElementById("btnUpdate").disabled = false;
}
}
function isNumberKey(evt) {
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
}
</script>
<script language="javascript" type="text/javascript" src="../Css/wcf_validate.js"></script>
</head>
<body>
<form id="form1" runat="server">
<div>
<br />
<div class="divEditHeader" id="EditHeader">
<h1>
Logging Configuration
</h1>
<table width="100%">
<tr>
<td align="left">
<asp:Button CssClass="formEditBtn" runat="server" ID="btnUpdate" Text="Update" OnClick="btnUpdate_Click"
Enabled="false" />
<button class="formEditBtn" onclick="javascript:setDefaults();" causesvalidation="false">
Default</button>
</td>
<td align="right">
</td>
</tr>
</table>
</div>
<br />
<table class="InputTable">
<tr class="Prompt">
<td class="Prompt">
Logging Level
</td>
<td>
<asp:DropDownList runat="server" ID="dlLoggingLevel">
<asp:ListItem Text="NONE" Value="none"></asp:ListItem>
<asp:ListItem Text="FATAL" Value="fatal"></asp:ListItem>
<asp:ListItem Text="ERROR" Value="error"></asp:ListItem>
<asp:ListItem Text="WARNING" Value="warning"></asp:ListItem>
<asp:ListItem Text="INFO" Value="info"></asp:ListItem>
<asp:ListItem Text="DEBUGLOW" Value="debuglow"></asp:ListItem>
<asp:ListItem Text="DEBUGMEDIUM" Value="debugmedium"></asp:ListItem>
<asp:ListItem Text="DEBUGHIGH" Value="debughigh"></asp:ListItem>
<asp:ListItem Text="DEBUGALL" Value="debugall"></asp:ListItem>
</asp:DropDownList>
<img id="imgLoggingLevel" src="../images/blank.png" />
<asp:TextBox runat="server" ID="dlLoggingLevel_Init" Style="display: none"></asp:TextBox>
<asp:TextBox runat="server" ID="dlLoggingLevel_Def" Style="display: none"></asp:TextBox>
<img id="imgLoggingLevelUndo" src="../images/restore.png" style="display: none; cursor: hand"
onmouseover="this.src='../Images/restore_hov.png'" onmouseout="this.src='../Images/restore.png'"
onclick="restoreValue('dlLoggingLevel','dlLoggingLevel_Init','imgLoggingLevel','imgLoggingLevelUndo')" />
</td>
<td>
<a href="javascript: void 0" class="info">
<img src="../images/help.png" border="0">
<span><font size="2">Enter the desired level of diagnostic data logging. Default: INFO.
</font></span></a>
</td>
</tr>
<tr class="Prompt">
<td class="Prompt">
Maximum Log File Size(MB)
</td>
<td>
<asp:TextBox runat="server" ID="txtMaxFileSize" Width="36px" MaxLength="3"></asp:TextBox>
<asp:TextBox runat="server" ID="txtMaxFileSize_Init" Style="display: none"></asp:TextBox>
<asp:TextBox runat="server" ID="txtMaxFileSize_Def" Style="display: none"></asp:TextBox>
<img id="imgMaxSize" src="../images/blank.png" />
<asp:CustomValidator runat="server" ID="valMaxSize" ControlToValidate="txtMaxFileSize"
Display="Dynamic" ErrorMessage="" ClientValidationFunction="MaxSize_Validate"></asp:CustomValidator>
<img id="imgMaxSizeUndo" src="../images/restore.png" style="display: none; cursor: hand"
onmouseover="this.src='../images/restore_hov.png'" onmouseout="this.src='../images/restore.png'"
onclick="restoreValue('txtMaxFileSize','txtMaxFileSize_Init','imgMaxSize','imgMaxSizeUndo')" />
</td>
<td>
<a href="javascript: void 0" class="info">
<img src="../images/help.png" border="0">
<span><font size="2">Enter the maximum log file size in MB. Default: 2 MB. Range: 1
- 100 MB. </font></span></a>
</td>
</tr>
</table>
<br />
<asp:Label runat="server" ID="lblMessage" Font-Bold="true"></asp:Label>
<br />
</div>
</form>
</body>
</html>
Code-Behind
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DiagnosticCommon;
using System.Drawing;
public partial class Settings_LogSettings : System.Web.UI.Page
{
const string EnvVariable = "DIAGNOSTICSERVER";
const string ConfigFileName = "DiagnosticService.exe.config";
protected void Page_Load(object sender, EventArgs e)
{
if (Security.EnforceSecurity())
Response.Redirect("Login.aspx");
if (!IsPostBack)
{
DebugHelper.MaxDebugLevel = DebugHelper.Parse(ConfigReader.GetValue("LoggingLevel"));
DebugHelper.MaxLogFileSize = long.Parse(ConfigReader.GetValue("LogFileSize"));
txtMaxFileSize.Attributes.Add("onchange", "javascript:MaxSize_Validate('',this);");
txtMaxFileSize.Attributes.Add("onkeypress", "return isNumberKey(event)");
dlLoggingLevel.Attributes.Add("onchange", "javascript:Logging_Validate('',this);");
BindData();
BindInitData();
BindDefaults();
}
}
private void BindData()
{
string installPath = Environment.GetEnvironmentVariable(EnvVariable);
try
{
dlLoggingLevel.SelectedValue = ConfigReader.GetValue("LoggingLevel");
txtMaxFileSize.Text = ConfigReader.GetValue("LogFileSize");
}
catch (Exception ex)
{
lblMessage.Text += ex.Message + "<br>" + installPath;
lblMessage.ForeColor = Color.Red;
}
}
private void BindInitData()
{
string installPath = Environment.GetEnvironmentVariable(EnvVariable);
try
{
dlLoggingLevel_Init.Text = ConfigReader.GetValue("LoggingLevel");
txtMaxFileSize_Init.Text = ConfigReader.GetValue("LogFileSize");
}
catch (Exception ex)
{
lblMessage.Text += ex.Message + "<br>" + installPath;
lblMessage.ForeColor = Color.Red;
}
}
protected void btnCancel_Click(object sender, EventArgs e)
{
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
}
protected void btnUpdate_Click(object sender, EventArgs e)
{
try
{
lblMessage.Text = "";
ConfigReader.SetValue("LoggingLevel", dlLoggingLevel.SelectedValue);
ConfigReader.SetValue("LogFileSize", txtMaxFileSize.Text);
lblMessage.Text = "Configuration updated.";
lblMessage.ForeColor = Color.Green;
btnUpdate.Enabled = false;
BindInitData();
}
catch (Exception ex)
{
lblMessage.Text += ex.Message;
lblMessage.ForeColor = Color.Red;
}
}
private void BindDefaults()
{
try
{
dlLoggingLevel_Def.Text = ConfigReader.GetDefault("LoggingLevel");
txtMaxFileSize_Def.Text = ConfigReader.GetDefault("LogFileSize");
}
catch (Exception ex)
{
lblMessage.Text = ex.Message;
lblMessage.ForeColor = Color.Red;
btnUpdate.Enabled = false;
}
}
}
Since the button has no type defined, the default type is used which is a submit button.
This means that when you click the Default button, the JS code is running but then the form is submitted.
To avoid the submission simply make the button be ordinary button:
<button type="button" class="formEditBtn" onclick="javascript:setDefaults();" causesvalidation="false">Default</button>
Following is the line in setDefaults() method that enables the update button for a while, a post back occurs and update button again disabled.
document.getElementById("btnUpdate").disabled = false;
Either comment this line or set it to true

How to get the Id of Checkbox which is inside a Repeater

I have a repeater inside which i put a Checkbox and above rapeater there is a HTML checkbox which is used to Check/Uncheck a Checkbox which is inside repeater using client side javascript.
Here is my Code:
JavaScript for Check/Uncheck:
<script type="text/javascript">
function selectAll() {
for (i = 0; i < document.all.length; i++) {
alert("Working");
if (document.all[i].type == 'checkbox') {
if (document.getElementById(cbSelectAll).Checked = true) {
//document.all[i].Checked = false;
} else {
document.all[i].Checked = true;
}
}
}
}
</script>
HTML Code for Repeater:
<div id="hdPropertyList" runat="server">
<table border="0" cellpadding="0" cellspacing="0" class="navigation" width="100%">
<tr>
<td>
<input type="checkbox" id="cbSelectAll" onchange="selectAll()" />
<asp:Button runat="server" ID="btnContactAll" Text="Contact All" />
</td>
<td id="tdOrderBy" runat="server">
</td>
<td>
<asp:Label ID="lblPage" runat="server" CssClass="pageList"></asp:Label>
</td>
</tr>
</table>
</div>
<div class="boxleft SearchFeaturedlist" style="display: none">
<h2>
Featured Properties</h2>
</div>
<asp:Repeater ID="rptPropertyList" runat="server" EnableViewState="false" OnItemDataBound="rptPropertyList_ItemDataBound"
OnLoad="rptPropertyList_Load">
<ItemTemplate>
<table id="propertyTable" runat="server" enableviewstate="false">
<tr id="tbrLabel" runat="server" enableviewstate="false">
<td id="tbcLabel" colspan="3" runat="server" enableviewstate="false">
</td>
</tr>
<tr id="tbrTitle" runat="server" enableviewstate="false">
<td id="tbcTitle" runat="server" enableviewstate="false">
<asp:CheckBox ID="ChkSelect" runat="server" /><span id="spnSelect" runat="server"></span>
</td>
</tr>
</table>
<div id="divAds" runat="server" visible="false" enableviewstate="false" style="width: 100%;
overflow: hidden">
</div>
</ItemTemplate>
</asp:Repeater>
Please help me in this regards.
Thanks in Advance.
The ID of the repeater will be available through it's ClientID property.
Really, you want to be asking whether you need this at all. Why not place the repeater inside a named div, and then simply find all input elements that have a type of checkbox that reside within it ( getElementsByTagName would help here ).
With a decent js addon library, like mootools or jQuery, you'll be able to use CSS selectors, which will make your task even easier.
Here's mootools example :-
function selectAllOrNone()
{
var myNewValue = $('selectall').innerText == "All" ? "None" : "All";
var myCheckers = $$('input[type=checkbox]');
$('selectall').innerText = myNewValue;
myCheckers.each(
function(e) {
e.checked = (myNewValue == "None");
}
);
}
I got the answer using Jquery. I used only the HTML checkbox to Check Uncheck all the checkbox on my Asp.net page.
<script type="text/javascript">
$(document).ready(function() {
$('td.title_listing :checkbox').change(function() {
$('#cbSelectAll').attr('checked', false);
});
});
function CotactSelected() {
var n = $("td.title_listing input:checked");
alert(n.length);
var s = "";
n.each(function() {
s += $(this).val() + ",";
});
window.location = "/D_ContactSeller.aspx?property=" + s;
alert(s);
}
Thanks to "Paul Alan Tylor" for your guidance.

Categories