asp.net javascript - asp.net

I am writing a javascript in asp.net server side (with in a button click event), this script is called if the user id and password matches and it supposed to close current window and open welcome page, but it is not happening. Below is my code, can anyone help me figure out what is the problem?
protected void okbtn_Click(object sender, EventArgs e)
{
account.txtuser = txtuid.Text;
account.txtpwd = txtupwd.Text;
account.login();
if (account.data == true)
{
string script = "<script language='javascript' type='text/javascript'>function f11(){window.close();var strLocation ;var strProfileID ;if (top.opener == null){strLocation = 'YourAccount.aspx';window.location = strLocation;}else{strLocation = 'http://' + top.opener.location.hostname+':'+ window.location.port + '/SendMail/' + 'YourAccount.aspx';top.opener.location = strLocation;top.opener.focus();}}</script>";
ClientScript.RegisterStartupScript(GetType(),"abc", script, true);
}
else
{
Label1.Text = "Invalid user name or password";
}
}

Add a OnClientClick event instead. For example:
<asp:Button id="okbtn" runat="server" text="OK" OnClientClick="window.close();" />
As for registering the startup script, you'd probably want to do this on Page_Load.

ClientScript.RegisterStartupScript(GetType(), "abc", script, true);
if you pass true argument at the end of the function parameters you don't need to add tags in your javascript codes because true means " tags will automatically wrap your javascript code"
Try in this way. If it doesn't help, please let us know.

Don't include <script></script> tag.
string script = "setTimeout(f11,10); function f11(){ window.close();}";
ClientScript.RegisterStartupScript(GetType(), "abc", script, true);

Related

response.redirect not working in chrome or firefox

i have a problem .i'm grateful to answer.
i have a Gridview that included a button at one its column (inside itemtemplate).
i wrote a program inside Gridview rowcommand event for button that used response.redirect to self page.
but this response.redirect not working at chrome or firefox.
but working in IE correctly.
You can detect the browser type/name like
HttpBrowserCapabilities bc = Request.Browser;
string bname = bc.Browser;
Then check if bname contains words like firefox/chrom (use a if condition) then redirect through JS client script like, else use response.redirect
string PageUrl = "http://www.someurl.com";
ClientScript.RegisterClientScriptBlock(this.GetType(), "someKeyRedir",
"window.location.href = '" + PageUrl + "';", true);
i'm grateful to answer. my code is:
public void G2_RowCommand(object sender, GridViewCommandEventArgs e)// in GridView,each button that be clicked,call this Gridview event
{
if (e.CommandName == "edit")//if this condition was true ,
{
Session.Remove("type");
Session.Add("taskReport_id",e.CommandArgument.ToString());
Response.Redirect("Default3.aspx#3");
}
}
I tried below but this not working also
Page.ClientScript.RegisterStartupScript(Page.GetType(), "script", "window.location.href='Default3.aspx#3';", true);

Getting the value of a hidden field

I have an ASP.NET page with three hidden fields. (Just one would do if I can get it to work. Just showing that I've tried several things.)
<input type="hidden" id="hiddenSkillId1" runat="server" />
<input type="hidden" id="hiddenSkillId2" />
<asp:HiddenField ID="hiddenSkillId3" runat="server"/>
I also have a JavaScript function that is being called by an AJAXControlToolKit.AutoCompleteExtender.OnClientItemSelected event:
<script type="text/javascript">
function SkillPartialMatchSelected(source, eventArgs ) {
document.getElementById("ctl00_Content_hiddenSkillId1").Value = eventArgs.get_value();
document.getElementById("hiddenSkillId2").Value = eventArgs.get_value();
document.getElementById("ctl00_Content_hiddenSkillId3").Value = eventArgs.get_value();
}
</script>
Using a break point and inspecting the values, I have confirmed that the vales are being set on the Client side.
Finally I have C# code behind for the page that is connected to a LinkButton OnClick event.
protected void AddSkillToProspect(object sender, EventArgs e)
{
string selectedKey1 = Request.Form[hiddenSkillId1.ClientID];
string selectedKey2 = Request.Form["hiddenSkillId2"];
string selectedKey3 = Request.Form[hiddenSkillId3.ClientID];
string selectedItem = SkillNameBox.Text.Trim();
...
}
All three selectedKey values are null but the selectedItem value from the ASP.NET Text Edit has a value.
From what I've read, one of these should work. Am I missing something? What can I do to get the value from a JavaScript function on the client side back to the server side?
The problem is related to case-sensitivity in JavaScript. Although you have set the .Value for these fields, that is not the same as the .value. Change your javascript to set the .value and you should be all set.
<script type="text/javascript">
function SkillPartialMatchSelected(source, eventArgs )
{
document.getElementById("ctl00_Content_hiddenSkillId1").value = eventArgs.get_value();
document.getElementById("hiddenSkillId2").value = eventArgs.get_value();
document.getElementById("ctl00_Content_hiddenSkillId3").value = eventArgs.get_value();
}
</script>
your hiddens controls have runat=server on them means they are server control and you can access them by their id in your code behind
this way the difference will hiddenSkillId1 is a htmlserver control, hiddenSkillId2 normal html control and this one hiddenSkillId3 is an asp.net control
string selectedKey1 = hiddenSkillId1.Value;
string selectedKey3 = hiddenSkillId3.Text;
string selectedKey2 = Request.Form[hiddenSkillId2];
So please try using it this way

How to set maxlength for multiline TextBox?

When using a MultiLine TextBox (which generates a TextArea) setting the MaxLength property has no effect. What is the best workaround? I'd like to get basic, intended functionality with minimum of ugly javascript etc. Just prevent user from entering more than max number of characters.
If you don't care about older browsers (see supported browsers here),
you can set MaxLength normally like this
<asp:TextBox ID="txt1" runat="server" TextMode="MultiLine" MaxLength="100" />
and force it to be printed out to the HTML
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
txt1.Attributes.Add("maxlength", txt1.MaxLength.ToString());
}
If you want to let the user know if he exceeded the amount of characters as he writes, you could use a javascript function attached to keypress event. This function would test the length of the input and cancel the character rendering if the maxlenght was reached.
Another option is to use RegularExpressionValidator control to validate the input on submit.
In my opinion, the first option is much more better.
I'm not adding any code since google is full of examples for all tastes, this is a very common task.
Here you have a sample search that might help.
Hey pukipuki you can do as follows:
<asp:TextBox ID="txtValue" runat="server"TextMode="MultiLine" Rows="10"Columns="50"></asp:TextBox>
$(document).ready(function(){
var MaxLength = 250;
$('#txtValue').keypress(function(e)
{
if ($(this).val().length >= MaxLength)
{
e.preventDefault();
}
});});
You can see more in this following link:
http://jquerybyexample.blogspot.in/2010/10/set-max-length-for-aspnet-multiline.html
Here's a cross browser solution :
<asp:TextBox TextMode="MultiLine" runat="server" ID="txtPurpose" Columns="50" Rows="2" onkeypress="return isokmaxlength(event,this,255);" ClientIDMode="static"></asp:TextBox>
Javascript :
function isokmaxlength(e,val,maxlengt) {
var charCode = (typeof e.which == "number") ? e.which : e.keyCode
if (!(charCode == 44 || charCode == 46 || charCode == 0 || charCode == 8 || (val.value.length < maxlengt))) {
return false;
}
}
You have to think about the Copy and Paste. This is a little bit tricky, I simply disable it with Jquery. But you can create your own function to do more complex verification. But in my case, copy and paste is not allowed.
Jquery to disable copy and paste :
jQuery(function ($) {
$("#txtPurpose").bind({
paste: function (e) {
e.preventDefault();
}
});
});
If you are using a model object bind to that textbox you can use DataAnnotations attributes to set the maxlength of that property. I'm based on MVC about that but it should work for ASP.NET too!
This way you don't mess with any Javascript or setting anything in the markup.
Try this..
Dim script As String = ""
script = script + " <script type='text/javascript'> function CheckLength(obj) {"
script = script + " var object = document.getElementById(obj);"
script = script + " if (object.value.length > 5) {"
script = script + " object.focus();"
script = script + " object.value = object.value.substring(0, 5); "
script = script + " object.scrollTop = object.scrollHeight; "
script = script + " return false;"
script = script + " }"
script = script + " return true;"
script = script + " }</script>"
Dim b As New TextBox()
b.ID = "btnSomeButton"
b.TextMode = TextBoxMode.MultiLine
Mypanel.Controls.Add(b)
b.Attributes.Add("onkeyup", "return CheckLength('" & b.ClientID & "');")
Page.ClientScript.RegisterStartupScript(Page.GetType(), "key", script, False)
To force asp.net to send the maxlength attribute for all multiline textboxes on a page or a whole site,
building on Aximili's answer above:
Create a function to get all the controls on the page:
I use the control extension method from David Findley
https://weblogs.asp.net/dfindley/linq-the-uber-findcontrol
and referenced in this SO post
Loop through all controls on asp.net webpage
namespace xyz.Extensions
{
public static class PageExtensions
{
public static IEnumerable<Control> All(this ControlCollection controls)
{
foreach (Control control in controls)
{
foreach (Control grandChild in control.Controls.All())
yield return grandChild;
yield return control;
}
}
}
}
In the page or master page
Make sure to reference the namespace for the extension method in step 1.
Put the following code in the Page_Load function:
if (!IsPostBack){
//force textareas to display maxlength attribute
Page.Controls.All().OfType<TextBox>().ToList()
.Where(x => x.TextMode == TextBoxMode.MultiLine && x.MaxLength > 0)
.ToList().ForEach(t => t.Attributes.Add("maxlength", t.MaxLength.ToString()));
}

Avoid postback on button click

I have a Search feature. if the search string is empty and user clicks "GO" then the postback of the gridview shouldn't happen and the alert (as mentioned in below code) should get fired up.
My gridview is in update panel. Below is the logic that i have written but it doesn't works.
protected void btnGo_Click(object sender, EventArgs e)
{
if (!txtSearchString.Text.Equals(string.Empty))
{
BinGrid();
upnl1.update //update panel is updated here.
}
else
{
ScriptManager.RegisterStartupScript(this.upnl1, this.GetType(), "Search", "alert('Enter search text');", false);
//upnlgvOpportinities.Update();
//upnlAdmin.Update();
return;
}
}
Please help! Let me know if any info is needed
This logic is wrong. It should do using javascript if you want to avoid the postback at first place.
Have your javascript return false when textbox is empty and true when not
<asp:button runat="server".... OnClientClick="return myfunction(); " />
You can check if textbox is empty or not in myfunction()
Replace Your ScriptManager line with below code line.
ScriptManager.RegisterStartupScript(this.upnl1, this.GetType(), "Script", "alert('Enter search text');", true);
If you don't want a request to the server to be sent (if I understood your needs right), than you need a client-side solution, that is handle button click with javascript and conditionally prevent the postback. However your current code is server-side, and is executed on a server after the postback has occurred.
As to client-side, here is one possible way. Define a js function that simply checks the value of the search box and returns false if it is empty. On the button click simply call this function. If a click handler returns false, further processing of the button click will be stopped and the postback won't occur:
function checkSearch() {
var searchBox = document.getElementById('HereComesSearchBoxClientID');
if (searchBox.value == '') {
alert('Enter search text');
return false;
} else {
return true;
}
}
<asp:Button ID="SearchButton" runat="server" Text="GO" OnClick="ServerSideHandler" OnClientClick="checkSearch();" />
#Madhur Ahuja's way is the correct one. Expanding that a little bit more.
HTML
<asp:Button ID="txtSearchString" runat="server"
OnClientClick="javascript:return CheckifEmpty(this);" />
Javascript
function CheckifEmpty(objSearchBox) {
//always trim, otherwise it will accept a string of spaces
var isEmpty = objSearchBox.value.trim() == "";
if (isEmpty) {
alert('Enter search text');
}
return !isEmpty;
}
if (!String.prototype.trim) {
String.prototype.trim = function() {
return this.replace(/^\s*(\S*(?:\s+\S+)*)\s*$/, "$1");
};
}

Register javascript code from serverside

I have a Asp.Net control inside a updatepanel thet is inside a modal popup.
I wont to register write javascript code in client from the control code.
these is my code:
Dim output As String = .. javascript code
Page.ClientScript.RegisterClientScriptBlock(Me.GetType(), "frmulaMatrix", output, True)
these is my second thinf but dont work
Page.RegisterClientScriptBlock("SCRIPTNAME", "<script language='javascript'>" + output+"</script>")
You must be trying to do this within a partial post back.
You should do it like this.
ScriptManager scriptManager = ScriptManager.GetCurrent(Page);
if (scriptManager != null && scriptManager.IsInAsyncPostBack)
{
//if a MS AJAX request, use the Scriptmanager class
ScriptManager.RegisterStartupScript(Page, Page.GetType(), scriptKey, script, true);
}
else
{
//if a standard postback, use the standard ClientScript method
Page.ClientScript.RegisterStartupScript(Page.GetType(), scriptKey, script, true);
}
The second method is deprecated. Where in the page life cycle are you calling this code?
try without the script tags. I believe the script manager adds that automatically
script = #"function onBeginRequest myJavascript{
//bla bla
}
this.Page.ClientScript.RegisterStartupScript(this.GetType(), "frmulaMatrix", script, true);

Resources