asp.net button click event not working with firefox - asp.net

Following is the code that i am using. It work in IE but the button click event is not generated properly in firefox:
function trapEnter(btn,hdn, event) {
var key;
var isIE = true;
debugger;
if (window.event) {
key = window.event.keyCode; //IE
isIE = true;
}
else {
key = event.which; //firefox
isIE = false;
}
if (key == 13) {
var btn = document.getElementById(btn);
if (btn != null) { //If we find the button click it
document.getElementById(hdn).value = '1'
btn.click();
key = 0;
}
}
}

I think your function has the wrong parameters. Try this:
function trapEnter(e) {
e = e || window.event || event;
var code = e.charCode || e.keyCode || e.which;
if (code == 13) {
var btn = document.getElementById('<%= YourButtonID.ClientID %>');
if (btn != null) { //If we find the button click it
document.getElementById(hdn).value = '1';
btn.click();
key = 0;
}
}
}

Related

Get user.Identity.GetUserId() always null

I am using asp.net membership. I have login successfully but when I have access user than user.Identity.GetUserId() always null.
this is my login code.
var signinManager = Context.GetOwinContext().GetUserManager<ApplicationSignInManager>();
SignInStatus result = signinManager.PasswordSignIn(txtEmail.Text, txtPassword.Text, RememberMe.Checked, false);
switch (result)
{
case SignInStatus.Success:
string strReturnUrl = Request.QueryString["ReturnUrl"] ?? "";
if (string.IsNullOrWhiteSpace(strReturnUrl))
{
if (GenericMethods.CheckUserInRole(user, UserRoles.SystemAdmin.ToString()))
strReturnUrl = "~/Admin/SettingsMaster.aspx";
else if (GenericMethods.CheckUserInRole(user, UserRoles.Admin.ToString()))
strReturnUrl = "~/Admin/SettingsMaster.aspx";
else if (GenericMethods.CheckUserInRole(user, UserRoles.CorporateSponsor.ToString()))
strReturnUrl = "~/";
else if (GenericMethods.CheckUserInRole(user, UserRoles.Advertiser.ToString()))
{
int productcount = ProductBL.GetInactiveProductCount(user.Id);
if (String.IsNullOrEmpty(user.FirstName) || String.IsNullOrEmpty(user.LastName) ||
String.IsNullOrEmpty(user.Address1) || String.IsNullOrEmpty(user.PhoneNumber) ||
String.IsNullOrEmpty(user.Email) || String.IsNullOrWhiteSpace(user.Birthdate.ToString()))
{
strReturnUrl = "~/MyAccount/ProfileSetting.aspx";
}
else if (productcount > 0)
{
strReturnUrl = "~/MyAccount/ViewFeatureProduct.aspx";
}
else
strReturnUrl = "~/MyAccount/AdvertiserTutorial.aspx";
}
else if (GenericMethods.CheckUserInRole(user, UserRoles.Subscriber.ToString()))
{
int productcount = ProductBL.GetInactiveProductCount(user.Id);
if (String.IsNullOrEmpty(user.FirstName) || String.IsNullOrEmpty(user.LastName) ||
String.IsNullOrEmpty(user.Address1) || String.IsNullOrEmpty(user.PhoneNumber) ||
String.IsNullOrEmpty(user.Email) || string.IsNullOrWhiteSpace(user.Birthdate.ToString()))
{
strReturnUrl = "~/MyAccount/ProfileSetting.aspx";
}
else if (productcount == 0)
{
strReturnUrl = "~/MyAccount/TradeMyStuff.aspx";
}
else
strReturnUrl = "~/";
}
}
var userLoginInfo = new UserLoginInfo("ClosetAuctions.com", "CA");
userManager.AddLogin(user.Id, userLoginInfo);
user.LastLoginDate = DateTime.Now;
userManager.Update(user);
IdentityHelper.RedirectToReturnUrl(strReturnUrl, Response);
break;
case SignInStatus.LockedOut:
Response.Redirect("/Account/Lockout");
break;
case SignInStatus.RequiresVerification:
Response.Redirect(
String.Format("/Account/TwoFactorAuthenticationSignIn?ReturnUrl={0}&RememberMe={1}",
Request.QueryString["ReturnUrl"],
RememberMe.Checked),
true);
break;
// ReSharper disable once RedundantCaseLabel
case SignInStatus.Failure:
default:
FailureText.Text = "Invalid login attempt";
ErrorMessage.Visible = true;
break;
}
I am getting userId here.
public static ApplicationUser GetCurrentUser()
{
var user = HttpContext.Current.User;
if (user == null) return null;
if (user.Identity.GetUserId() == null) return null;
var db = new MyDbContext();
var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(db));
return manager.FindById(user.Identity.GetUserId());
// manager.AddClaim(CurrentUser.Id, new Claim(ClaimTypes.Role, "systemAdmin"));
// manager.AddClaim(CurrentUser.Id, new Claim(ClaimTypes.Role, "admin"));
}
I am not sure, where I am wrong.
If any one know then Can you please help me.
Maybe you check authentication first.
if (User.Identity.IsAuthenticated)
{
string userId = HttpContext.Current.User.Identity.Name;
}

OnClick and OnClientClick not working together in RadButton

IN RadButton OnClick Event and OnClient Event are not working together. Javascript is not called by OnClient Click in radbutton. I also use RadAjaxSetting.
<script language="javascript" type="text/javascript">
form_dirty = false;
calenderclink = false;
window.onbeforeunload = askUser;
function setSaveEnable() {
document.getElementById('ctl00_ContentPlaceHolder1_btnSave_85').disabled = false;
form_dirty = true;
calenderclink = false;
}
function form_dirty_true() {
document.getElementById('ctl00_ContentPlaceHolder1_btnSave_85').disabled = false;
form_dirty = true;
calenderclink = false;
}
function form_dirty_false() {
form_dirty = false;
calenderclink = false;
Calnederdirty = false;
}
function setSaveEnableforCalender() {
form_dirty = true;
calenderclink = true;
}
function askUser(evt) {
var vtxtSiv = '<%=HndDiscurdMessage.ClientID%>';
var message = document.getElementById(vtxtSiv).value;
if (form_dirty == true && calenderclink == false) {
if (typeof evt == 'undefined') {
evt = window.event;
}
if (evt) {
evt.returnValue = message;
}
return message;
}
else if (form_dirty == true && calenderclink == true) {
if (document.getElementById('ctl00_ContentPlaceHolder1_rdpWishDate').value != null) {
form_dirty = true;
calenderclink = true;
}
}
}
function ClearAlert() {
var _dvAlert = document.getElementById("<%# dvAlert.ClientID %>");
_dvAlert.attributes[2].value = "display: none;";
form_dirty_true();
}
</script>
<telerik:RadButton ID="btnSave_85" runat="server" CssClass="btnMain btngreen right topRightBtn" OnClientClick="form_dirty_false();" SingleClick="true"
Text="Save" OnClick="btnSave_Click" ></telerik:RadButton>
ONClick is working properly but on clientclick is not working.
Try this out.
<telerik:RadButton ID="btnSave_85" runat="server" CssClass="btnMain btngreen right topRightBtn" OnClientClick="form_dirty_false;" SingleClick="true"
Text="Save" OnClick="btnSave_Click" ></telerik:RadButton>
Then in your javascript have this:
function form_dirty_false(s,a) {
form_dirty_false(); // your original code
}

Resetting textbox text via javascript

function clickButton(e, buttonid)
var evt = e ? e : window.event;
var bt = document.getElementById(buttonid);
if (bt) {
if (evt.keyCode == 13) {
bt.click();
return false;
}
}
}
txtChatMessage.Attributes.Add("onkeypress", "return clickButton(event,'" + btnSendChat.ClientID + "')");
this function is an attribute that is set in code behind file. How do I reset the text in textbox after the button click fires
You can do it like this, by passing the text field from code behind using this, and setting its value to empty string in javascript
In code behind
txtChatMessage.Attributes.Add("onkeypress", "return clickButton(this, event,'" + btnSendChat.ClientID + "')");
In javascript
function clickButton(txt, e, buttonid){
var evt = e ? e : window.event;
var bt = document.getElementById(buttonid);
if (bt) {
if (evt.keyCode == 13) {
bt.click();
txt.value = "";
return false;
}
The above code will over write the existing value of text box. To save it for later use we can use hidden field
In html
<asp:hidden id="hdnText" runat="server" >
In javascript
function clickButton(txt, e, buttonid){
var evt = e ? e : window.event;
var bt = document.getElementById(buttonid);
if (bt) {
if (evt.keyCode == 13) {
bt.click();
document.getElementById('<%= hdnText.ClientID %>').value = txt.value;
return false;
}
In Code behind
Send text field to javascript function
txtChatMessage.Attributes.Add("onkeypress", "return clickButton(this, event,'" + btnSendChat.ClientID + "')");
Get value of textbox from hidden field
string textBoxValue = hdnText.Value;

Alert message not popping up though the dynamic textbox is empty

Below is the code how I am creating the dynamic textboxes. I want to validate if any of the dynamic textboxes created are empty and if yes, should throw an error message or alert to user prompting to fill up the textboxes on Additem button click. I get the alert message entered into the function, after which I don't receive any message alerting the user to fill in the textbox "xxxx".
Please help me to fix the code
if (ControlType == "TextBox")
{
int textBoxLength;
TextBox MynewTextBox = new TextBox();
MynewTextBox.ID = "txt" + Fldname;
MynewTextBox.Width = 100;
MynewTextBox.BorderStyle = BorderStyle.Solid;
MynewTextBox.Attributes.Add("Type", "T");
MynewTextBox.Attributes.Add("IsKeyField", "Y");
MynewTextBox.Attributes.Add("IsMandatory", "Y");
}
protected void Page_Load(object sender, EventArgs e)
{
btnAddItem.Attributes.Add("onClick", "if(!ValidateMandatoryFields()) return false;");
}
<script language="javascript" type="text/javascript">
function ValidateMandatoryFields() {
alert("entered into the function");
var inputControls = document.getElementsByTagName("input");
alert(inputControls.length);
for (var i = 0; i < inputControls.length; i++) {
if (inputControls[i].getAttribute("IsKeyField") == "Y") {
if (inputControls[i].getAttribute("Type") == "T" || (inputControls[i].getAttribute("Type") == "C")) {
if (inputControls[i].getAttribute("IsMandatory") == "Y") {
if (inputControls[i].value == "") {
alert(inputControls[i].getAttribute("KeyField_Name") + "is required.");
errorMsg += "\n" + inputControls[i].getAttribute("KeyField_Name") + " is required.";
isValidated = false;
}
}
}
}
}
}
}
</script>
enter link description here
i followed the link above
It still did not help me
function ValidateMandatoryFields() {
alert("entered into the function");
var inputControls = document.getElementsByTagName("input");
alert(inputControls.length);
for (var i = 0; i < inputControls.length; i++) {
if (inputControls[i].getAttribute("IsKeyField") == "Y") {
alert(inputControls[i]);
}
else {
alert("first if statemenet");
}
if (inputControls[i].getAttribute("Type") == "T" || (inputControls[i].getAttribute("Type") == "C")) {
alert(inputControls[i]);
}
else {
alert("second if statement");
}
if (inputControls[i].getAttribute("IsMandatory") == "Y") {
alert(inputControls[i]);
}
else {
alert("third if statement");
}
if (inputControls[i].value == "") {
alert(inputControls[i].getAttribute("KeyField_Name") + "is required.");--error here
errorMsg += "\n" + inputControls[i].getAttribute("KeyField_Name") + " is required.";
isValidated = false;
}
else {
alert("name: " + inputControls[i].id);
alert("length: " + inputControls[i].value.length());
alert("value: " + inputControls[i].value);
}
}
}
It pop ups of all else statements appear and finally i get a error stating Microsoft JScript runtime error: Object expected. Which means that none of my if condition is true...How do I get it to work...please help me with the correct logic
Try adding an else clause to see what the values are:
if (inputControls[i].value == "") {
... your code
} else
{
alert("name: " + inputControls[i].id);
alert("length: " + inputControls[i].value.length());
alert("value: " + inputControls[i].value);
}
It's possible they are set to null or spaces instead of just an empty string.
I was able to fix my code as shown below:
function validateInput() {
var arrTextBox = document.getElementsByTagName("input");
var retValue = 1;
var returnValue = 1;
for (i = 0; i < arrTextBox.length; i++) {
if (arrTextBox[i].type =="text" && arrTextBox[i].getAttribute("IsMandatory")=="Y" && arrTextBox[i].value == "") {
retValue = 0;
}
}
if (retValue == 0) {
alert("Validation Failed");
return false;
}
else {
alert("Validation Success");
return true;
}
on the ascx.cs file
btnAddItem.Attributes.Add("onclick", "{return validateInput()};");

javascript inside updatepanel

im using javascript in asp.net gridview
<script type="text/javascript">
var currentRowId = 0;
function SelectRow()
{
if (event.keyCode == 40)
MarkRow(currentRowId+1);
else if (event.keyCode == 38)
MarkRow(currentRowId-1);
}
function MarkRow(rowId)
{
if (document.getElementById(rowId) == null)
return;
if (document.getElementById(currentRowId) != null )
document.getElementById(currentRowId).style.backgroundColor = '#ffffff';
currentRowId = rowId;
document.getElementById(rowId).style.backgroundColor = '#ff0000';
}
</script>
<script type="text/javascript">
var TargetBaseControl = null;
window.onload = function()
{
try
{
//get target base control.
TargetBaseControl =
document.getElementById('<%= this.GridView1.ClientID %>');
}
catch(err)
{
TargetBaseControl = null;
}
}
function TestCheckBox()
{
if(TargetBaseControl == null) return false;
//get target child control.
var TargetChildControl = "chkSelect";
//get all the control of the type INPUT in the base control.
var Inputs = TargetBaseControl.getElementsByTagName("input");
for(var n = 0; n < Inputs.length; ++n)
if(Inputs[n].type == 'checkbox' &&
Inputs[n].id.indexOf(TargetChildControl,0) >= 0 &&
Inputs[n].checked)
return true;
alert('Select at least one checkbox!');
return false;
}
</script>
button control:
" Width="80px" CssClass="button" />
im using ajax update panel in gridview ...i control postback level but the script is not working inside the updatepanel
In your button_clicked event, you could use this method
ScriptManager.RegisterClientScriptBlock(Control, Type, String, String, Boolean)
More info below
http://msdn.microsoft.com/en-us/library/bb350750.aspx

Resources