how to create textbox selected event with asp.net - c# - c#

I was wondering how i can trigger an event when a textbox is selected or focused.
My textbox is an asp.net type.
<asp:TextBox ID="TB" runat="server"></asp:TextBox>
When the event is triggered, i would like to do something in code-behind with c#.
thanks in advance for your reply.

We do not have any textbox selected event in asp.net. You can try using text changed event of textbox or you can try using java script as below.
<head runat="server">
<title></title>
<script type="text/javascript">
function RefreshUpdatePanel() {
__doPostBack('<%= Code.ClientID %>', '');
};
</script>
<asp:TextBox ID="Code" runat="server" onkeyup="RefreshUpdatePanel();" AutoPostBack="true" OnTextChanged="Code_TextChanged"></asp:TextBox>
<asp:UpdatePanel ID="Update" runat="server">
<ContentTemplate>
<asp:DropDownList runat="server" ID="DateList" />
<asp:TextBox runat="server" ID="CurrentTime" ></asp:TextBox>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Code" />
</Triggers>
</asp:UpdatePanel>

oki, so i figured it out by reading on an article on a different page.
check link: http://codingresource.blogspot.no/2010/01/how-to-use-events-like-onblur-onfocus.html
instead of using onblur i use onclick

Their is no serverside onfocus event for asp textbox you can use textchanged event as follows.using update panel of ajax control you can avoid page refreshment.
<asp:TextBox ID="TextBox1" runat="server" AutoPostBack="True" ontextchanged="TextBox1_TextChanged1" ></asp:TextBox>
protected void TextBox1_TextChanged2(object sender, EventArgs e)
{
}
On Client side onfocus event You can invoke a c# webmethord through ajax call as follows
HTML SOURCE
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#TextBox1").focus(function () {
$.ajax({
type: "POST",
url: "Default.aspx/test",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
}
});
});
});
</script>
C# code
[WebMethod]
public static void test()
{
}

Related

Convert JS function with REST API call to ASP.Net C# code behind

HTML code below is a simplified code taken from c-sharpcorner. I would like to modify this and transfer all logic in code behind. What I would like to know is how to convert the function, AddEmp, if I transfer this to btnSave's Click method. This is my first time using REST API and still learning to use it. Any advise is greatly appreciated.
protected void btnSave_Click(object sender, EventArgs e)
{
}
HTML
<html>
<head runat="server">
<title>Code snippet taken from Vithal Wadje's article</title>
<script src="jquery-1.7.1.js" type="text/javascript"></script>
<script type="text/javascript">
function AddEmp() {
var Emp = {};
Emp.FirstName = $("#txtFirstName").val();
Emp.LastName = $("#txtLastName").val();
Emp.Company = $("#txtCompany").val();
$.ajax({
url:"<%=Page.ResolveUrl("/api/Emp/AddEmployees")%>",
type: "POST",
contentType: "application/json;charset=utf-8",
data: JSON.stringify(Emp),
dataType: "json",
success: function (response) {
alert(response);
},
error: function (x, e) {
alert('Failed');
alert(x.responseText);
alert(x.status);
}
});
}
$(document).ready(function ()
{
$("#btnSave").click(function (e) {
AddEmp();
e.preventDefault();
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
First Name <asp:TextBox runat="server" ID="txtFirstName" />
<br />
Last Name <asp:TextBox runat="server" ID="txtLastName" />
<br />
Company <asp:TextBox runat="server" ID="txtCompany" />
<br />
<asp:Button Text="Save" runat="server" ID="btnSave" />
</form>
</body>
</html>

Autofill City and State with Zip Code entry

Trying to get a form to autofill the City and State textboxes when I enter in the Zip Code.
The code below is what I'm trying to use. If I replace the <asp:TextBox> with a <input type..> it work's but I specifically need to use <asp:TextBox> for my fields. Does anyone have a tips on how I can get this to work?
Here is a jsfiddle of it working with input's: http://jsfiddle.net/7VtHc/5/
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.min.js"> </script>
<script type='text/javascript'>
$(window).load(function () {
$(document).ready(function () {
$("#zipTxtBox").keyup(function () {
var el = $(this);
if (el.val().length === 5) {
$.ajax({
url: "http://zip.elevenbasetwo.com",
cache: false,
dataType: "json",
type: "GET",
data: "zip=" + el.val(),
success: function (result, success) {
$("#cityTxtBox").val(result.city);
$("#stateTxtBox").val(result.state);
}
});
}
});
});
});
</script>
<div class="row">
<div class="col-xs-6">
<asp:Label ID="Label13" runat="server" Text="Zip Code" />
<asp:TextBox ID="zipTxtBox" runat="server" />
</div>
<div class="col-xs-3">
<asp:Label ID="Label15" runat="server" Text="City" />
<asp:TextBox ID="cityTxtBox" runat="server" />
</div>
<div class="col-xs-2">
<asp:Label ID="Label16" runat="server" Text="State" />
<asp:TextBox ID="stateTxtBox" runat="server" />
</div>
</div>
in order to use ASP.NET Server Controls you need to use their ID's (if you see the source code, your textbox have a weird id, and not the one you specified in the ID attribute of the control.
If you're using an old version of WebForms (below .NET 3.5 - inclusive) you need to use:
$("#<%= cityTxtBox.ClientID %>").val(result.city);
$("#<%= stateTxtBox.ClientID %>").val(result.state);
the same when you pull the zip code:
$("#<%= zipTxtBox.ClientID %>").keyup( ...
if you have a recent WebForms version (.NET 4+) all you need to set is set ClientIDMode to static and then you can use the normal code as you had, like:
<asp:TextBox ID="cityTxtBox" ClientIDMode="static" runat="server" />
more on static controls in Scott's Guthrie blog entry

onChange and onSelectedIndexChanged events not firing - selectbox

I was able to implement the selectbox but onchange and OnSelectedIndexChanged are not firing. Any insights?
<div class="hasJS">
<asp:DropDownList class="custom" ID="myid" runat="server" OnSelectedIndexChanged="change" OnTextChanged="change" onChange="myChange();">
<asp:ListItem>Hello</asp:ListItem>
<asp:ListItem>Hello1</asp:ListItem>
<asp:ListItem>Hello3</asp:ListItem>
<asp:ListItem>Hello4</asp:ListItem>
<asp:ListItem>Hello5</asp:ListItem>
<asp:ListItem>Hello6</asp:ListItem>
<asp:ListItem>Hello7</asp:ListItem>
<asp:ListItem>Hello8</asp:ListItem>
</asp:DropDownList>
</div>
<script type="text/javascript">
$(function () {
$("select.custom").each(function () {
var sb = new SelectBox({
selectbox: $(this),
height: 150,
width: 200
});
});
});
function myChange() {
alert("Hai");
}
</script>
set autopostback=true for DropDownList ;
<asp:DropDownList class="custom" autopostback="true" ID="myid" runat="server" OnSelectedIndexChanged="change" OnTextChanged="change" onChange="myChange();">
i just copied your code and guess what it was working fine with AutoPostBack="True",first it shows alert message then twice event was getting fired for both event.i guess you must have implemented below snippet in your code behind file.
protected void change(object sender, EventArgs e)
{
}
for the case of onChange add return to the javascript call
<asp:DropDownList ID="cbProduct" runat="server"
CssClass="common_transaction_textbox_style" onchange="return LoadProductBatchByName();" Height="23px" Width="200px">
</asp:DropDownList>
function LoadProductBatchByName() {
{
alert('test');
}

Call server-side method in the onclick method in jQuery

I have one method in backend coding using c#. Now, I want to call it on onClick event of button using jQuery which is in design part.
Please help me to solve the problem.
Check out below code for example.
.aspx Page
$("#SubmitButton").click(function() {
// Call method BindData();
});
.aspx.cs Page
public void BindData()
{
// Code to bind datalist
}
ASPX
<script type="text/javascript">
function myFunction() {
// some stuff
return true; // important
}
</script>
<asp:Button runat="server" ID="SubmitButton"
OnClientClick="return myFunction();"
OnClick="SubmitButton_Click" />
Code-behind
protected void SubmitButton_Click(object sender, EventArgs e)
{
BindData();
}
By specifying OnClientClick you're telling your button that it should first execute the Javascript method. If the method returns false, there is no postback. However, if it returns true, the button's handler in code-behind will also be called.
if i understand right you want something like this
$("#SubmitButton").click(function() {
$.ajax({
type: "POST",
url: "index.aspx/BindData",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ }),
dataType: "json",
});
});
and make your method static and add attribute WebMethod like:
[WebMethod]
public static void BindData()
{
// Code
}
but you will not be able to change the state of server controls
in your css :
.hide
{
display:none;
}
then
<asp:Button runat="server" id="btn" onclick="btn_OnClick" CssClass="hide"/>
<div onclick="TestCall();return true;">Click Me !!</div>
<script type="text/javascript">
function TestCall()
{
var btn = $('#<%= btn.ClientID %>');
btn.click();
}
</script>
hope , helps you ;)
Add a APSBUTTON set onclick method on code behind then set CssClass to Hide means declare a style class contain display:none like this
<style>
.hide
{
display:none;
}
</style>
Button Sample :
<asp:Button ID="Button1" runat="server" Text="Button" CssClass="hide" OnClick="Button1_Click" />
JavaScript Sample :
<script type="text/javascript">
//With jQuery
$('#<%=Button1.ClientID%>').click();
</script>
that should be work for this case
good luck

Button in GridView in UpdatePanel Throws "Invalid postback or callback argument" on Click

I'm trying to make a jQuery confirm dialog call a web method. The dialog is called when the delete button in a GridView in an UpdatePanel is clicked.
However, when I click on the button, an error "Invalid postback or callback argument." I searched through some of the questions/answers here and tried overriding the Render event to register the UpdatePanel.
Here's my aspx page:
<%# Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
CodeBehind="Default.aspx.cs" Inherits="DoPostBack._Default" %>
<asp:Content ID="conStyles" runat="server" ContentPlaceHolderID="cphStyles">
</asp:Content>
<asp:Content ID="conMain" runat="server" ContentPlaceHolderID="cphMain">
<asp:UpdatePanel ID="upMovies" runat="server" UpdateMode="Conditional" onload="upMovies_Load">
<ContentTemplate>
<asp:GridView ID="gvItems" runat="server" CssClass="tbl-movies" AutoGenerateColumns="False">
<Columns>
<asp:BoundField DataField="Title" HeaderText="Title" HeaderStyle-CssClass="col-title-header" ItemStyle-CssClass="col-title"/>
<asp:BoundField DataField="Director" HeaderText="Director" HeaderStyle-CssClass="col-director-header" ItemStyle-CssClass="col-director" />
<asp:BoundField DataField="Year" HeaderText="Year" HeaderStyle-CssClass="col-year-header" ItemStyle-CssClass="col-year" />
<asp:TemplateField ItemStyle-HorizontalAlign="Left" ItemStyle-CssClass="table-actions">
<ItemTemplate>
<asp:ImageButton ID="btnEdit" ImageUrl="Images/edit.png" runat="server"
Text="Edit" UseSubmitBehavior="False" />
<asp:ImageButton ID="btnDelete" ImageUrl="Images/delete.png" runat="server"
Text="Delete" UseSubmitBehavior="False" CssClass="btn-delete-movie" />
<asp:HiddenField ID="hfMovieId" runat="server" Value='<%# Eval("Id") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
<div id="confirmDelete" class="popup popup-confirm">
<div class="popup-title">
<h4>Delete Movie</h4>
</div>
<div class="popup-content">
<div class="confirm-message">
</div>
<div class="buttons center">
<input id="btnDeleteConfirm" type="button" value="OK" class="button btn-confirm" />
<input id="btnDeleteCancel" type="button" value="Cancel" class="button btn-delete-cancel btn-close-popup" />
</div>
</div>
</div>
</asp:Content>
<asp:Content ID="conScripts" runat="server" ContentPlaceHolderID="cphScripts">
<script src="Scripts/site.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
var btnDelete = $('.btn-delete-movie');
btnDelete.on('click', function (e) {
e.preventDefault();
var row = $(this).closest('tr'),
title = row.find('.col-title').text(),
movieId = parseInt(row.find('input[type=hidden]').val());
showConfirmPopUp('confirmDelete',
'Are you sure you want to delete the movie "' + title + '"?',
function () { deleteMovie(movieId); }, //call the DeleteMovie web method
function () { }); //do nothing else
});
});
function deleteMovie(id) {
$.ajax({
type: 'POST',
contentType: 'application/json',
data: '{"id":' + id + '}',
url: 'Default.aspx/DeleteMovie',
dataType: 'json',
success: function (data) {
__doPostBack('<%= upMovies.ClientID %>', '');
closePopUp('confirmDelete');
},
error: function (jqXHR, textStatus, errorThrown) {
showError(jqXHR, textStatus, errorThrown);
}
});
}
</script>
</asp:Content>
Code-behind:
public partial class _Default : System.Web.UI.Page
{
#region Events
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
PopulateMovies();
}
}
protected override void Render(HtmlTextWriter writer)
{
ClientScript.RegisterForEventValidation(upMovies.UniqueID);
foreach (GridViewRow row in gvItems.Rows)
{
var btnDelete = row.FindControl("btnDelete");
var btnEdit = row.FindControl("btnEdit");
ClientScript.RegisterForEventValidation(btnDelete.UniqueID);
ClientScript.RegisterForEventValidation(btnEdit.UniqueID);
}
base.Render(writer);
}
protected void upMovies_Load(object sender, EventArgs e)
{
PopulateMovies();
}
#endregion
#region Private Methods
private void PopulateMovies()
{
var data = from m in Movie.GetAll()
orderby m.Year descending, m.Title ascending
select m;
gvItems.DataSource = data;
gvItems.DataBind();
}
#endregion
#region Web Methods
[WebMethod]
public static object DeleteMovie(int id)
{
Movie.Delete(id);
return UpdateItems();
}
#endregion
}
I'm using the jQuery approach because I don't want to use the ModalPopupExtender. I don't want to set EnableEventValidation to false either.
Also, why is the upMovies_Load called when I click on the delete button? Shouldn't it only be called when the ok button of the confirm dialog is clicked?
I'm kind of a beginner, help would be greatly appreciated.
Thank you :)
Okay, you have to rebind the JavaScript again via
Sys.WebForms.PageRequestManager.GetInstance().add_endRequest(function(){
//$(document).ready() code here
});

Categories

Resources