native html element input bind to asp.net event behind code - c#

hello guys im using a normal element "input text" now what im trying to do is bind my "input text" into an event handler under asp.net behind code method sample
normal scenario using asp.net element
aspx
<asp:TextBox ID="txtasptext" runat="server" OnTextChanged="txtasptext" ></asp:TextBox>
aspx.cs
protected void txtasptext(object sender, EventArgs e)
{
string name = "hello asp element";
}
but my goal is using normal element text, see below
aspx
<input type="text" id="txtnormaltext" runat="server" />
aspx.cs
protected void txtnormaltext(object sender, EventArgs e)
{
string name = "hello normal element";
}
need some help thanks and happy new year everyone

You could use javascript and AJAX call a web service:
<script>
function doSomething()
{
var params = $('#txtnormal').val();
$.ajax({
type: "POST",
url: "AjaxHandler.asmx/DoSomethingMethod",
data: params,
dataType: "json",
error: function (e) { alert('exception:' + e); }
});
}
</script>
HTML:
<input type="text" id="txtnormaltext" onchange="doSomething()" />
AjaxHandler.asmx Web Service:
[WebMethod]
public void DoSomethingMethod(string inputText)
{
//your code
}

For this HTML control you need to find it from your page_load and bind methods to it.
HtmlGenericControl mytxtbox =(HtmlGenericControl) FindControlRecursive(pnl, "textboxID");
mytxtbox.Attributes.Add("textbox_event_name", "Your_C#_Function");
View the FindControlRecursive function from Here

Related

How to trigger blockui from c#?

I'm looking for a way to trigger BlockUI from the code behind. I have server-side validations and I would not want the BlockUI to fire unless the server validations are complete.
Here's my button :
<asp:Button ID="BtnSave" runat="server" OnClick="BtnSaveUpdate_Click" Text="Save" CausesValidation="true"></asp:Button>
Code behind:
This is what I tried doing but this doesn't work:
protected void BtnSaveUpdate_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
ClientScript.RegisterStartupScript(typeof(Page), "blockui", " $.blockUI({ message: 'Saving Record...' });", true);
// remaining code...
}
}
This is my original javascript code which fires before server validation:
$(document).ready(function () {
$('#BtnSave').click(function () {
$.blockUI({
message: 'Saving Record...'
});
});
});

JS function calling from the code behind Issue

I have a JS function (Show alert box), and have a link button in ASP page, On click event from code behind for this link button I want to call this function and then redirect to certain page.
ASP Code
<script type="text/javascript" language="javascript">
function myFunction() {
// executes when HTML-Document is loaded and DOM is ready
alert("document is ready!");
}
</script>
<div>
<asp:LinkButton ID="lnkbtnChangePassword" runat="server" Text="Change Passwrod" OnClick="lnkbtnChangePassword_Click" ></asp:LinkButton>
</div>
C# Code
protected void lnkbtnChangePassword_Click(object sender, EventArgs e)
{
ClientScript.RegisterStartupScript(this.GetType(), "CallMyFunction", "myFunction()", true);
Response.Redirect("myPage.aspx");
}
Here when I click on the link button, it simply don't display the alert box/window and redirect to the page.
You should use LinkButton.ClientClick instead of LinkButton.Click event.
Click event is handled on server. When user clicks the button, page is posted back to server and code is executed on server side.
ClientClick event is really a name of JavaScript function which should be executed.
You should probably do something like this:
<asp:LinkButton ID="lnkbtnChangePassword" runat="server" Text="Change Passwrod" OnClientClick="showMyAlertAndSubmit()"></asp:LinkButton>
<script type="text/javascript">
function showMyAlertAndSubmit(){
alert("Your password is being changed");
// submit your form
}
</script>
Why your current code doesn't work
You currently send script for showing a message, and redirect at the same time. This means that browser receives instructions to show a message and to redirect, and it redirects the user before showing the message. One approach could be to redirect from client side. For example:
protected void lnkbtnChangePassword_Click(object sender, EventArgs e)
{
ClientScript.RegisterStartupScript(this.GetType(), "CallMyFunction", "myFunction()", true);
}
and on client side
function myFunction() {
// show your message here
// do other things you need
// and then redirect here. Don't redirect from server side with Response.Redirect
window.location = "http://myserver/myPage.aspx";
}
Other options
Since you need to first perform checks on server side before saving data and redirecting, you can use ajax to call server without performing postback.
Remove Click handler, and only use ClientClick:
function myFunction() {
$.ajax({
type: "POST",
url: "myPage.aspx/MyCheckMethod",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
ShowAlert();
window.location = "http://myserver/mypage.aspx";
}
});
}
For more details please check this tutorial.
Change your code like this:
ASP Code
<script type="text/javascript" language="javascript">
function myFunction() {
// executes when HTML-Document is loaded and DOM is ready
alert("document is ready!");
}
</script>
<div>
<asp:LinkButton ID="lnkbtnChangePassword" runat="server" Text="Change Passwrod" OnClick="lnkbtnChangePassword_Click" OnClientClick="myFunction()" ></asp:LinkButton>
</div>
C# Code
protected void lnkbtnChangePassword_Click(object sender, EventArgs e)
{
Response.Redirect("myPage.aspx");
}
Change your javascript function to :
<script type="text/javascript" language="javascript">
function myFunction() {
// alert will stop js execution
alert("document is ready!");
// then reload your page
__doPostBack('pagename','parameter');
}
</script>
And call it from code-behind with this function :
protected void lnkbtnChangePassword_Click(object sender, EventArgs e)
{
//do your job here
//then call your js function
ScriptManager.RegisterStartupScript(this,this.GetType(), "CallMyFunction", "myFunction();", true);
}
What you're missing is waiting for JavaScript alert dialog to popup and then redirect to the page.
In order to do this you need to tell button to wait for JavaScript alert dialog to popup and then do the Server side work after.
ASPX:
<head runat="server">
<title></title>
<script type="text/javascript">
function alertBeforeSubmit() {
return alert('Document Ready');
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button Text="Do" runat="server" ID="btnSubmit" OnClick="btnSubmit_Click" OnClientClick="return alertBeforeSubmit();" />
</div>
</form>
</body>
CS:
protected void btnSubmit_Click(object sender, EventArgs e)
{
Response.Redirect("Default.aspx");
}

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

how can i redirect to another page in function that called by btnclick. ASP.NET

I wanna redirect to another page when i call a function
here my button
<button id="test" runat="server" onclick="Button1_Click()"> Button here </button>
here my button action
protected void Button1_click(Object sender, EventArgs e)
{
int ID = 0;
Label5.Visible = false;
ID = Convert.ToInt32(GridView1.Rows[row.RowIndex].Cells[1].Text);
// somthing like
// Server.Transfer("~/Producter/Delete?id="+ id)
// OR
Response.Redirect("~/Producter/Delete?id="+ ID);
}
since you are using regular html button, when clicked, it will execute Button1_Click() on the client side, instead of in code behind.
Change the button to :
<asp:Button ID="test" runat="server" OnClick="Button1_Click" Text="Button here" />
It could be a problem with the binding of the function Button1_Click() to the button. Try checking the Button1's OnClick property to make sure it links to the function Button1_Click().
your Button1_Click function is correct, and I think the way you are calling from object is wrong.
you should either use
<asp:Button ID="btn_test" runat="server" OnClick="Button1_Click" Text="Button" />
protected void Button1_click(Object sender, EventArgs e)
{
int ID = 0;
Label5.Visible = false;
ID = Convert.ToInt32(GridView1.Rows[row.RowIndex].Cells[1].Text);
Response.Redirect("~/Producter/Delete?id="+ ID);
}
or you should use html button object and call a webmethod like below
<script>
$(document).ready(function () {
$('#test').click(function(){
$.ajax({
type: "POST",
url: "Profile.aspx/update_phone",
data: "{'ProfessionalID':''}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function () { }
});
});
});
</script>
<button id="test" runat="server"> Button here </button>
[webmethod]
public static void Button1_click(Object sender, EventArgs e)
{
....
Response.Redirect("~/Producter/Delete?id="+ ID);
}
Try this
Response.Redirect("~/Producter/Delete?id="+ ID,false);
try this;
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script type="text/javascript">
$('#test').on('click', function(e){
e.preventDefault();
//using jquery, you must import jquery library for it
$('#buttonHidden').click();
}
</script>
// your button here to call javascript
<button id="test" runat="server"> Button here </button>
// the hidden button just to hold the Button1_Click which is fired from fireClick()
<asp:Button ID="buttonHidden" runat="server" Style="display: none" OnClick="Button1_Click" />
also fix your code behind like this;
protected void Button1_Click(Object sender, EventArgs e)
{
int ID = 0;
Label5.Visible = false;
ID = Convert.ToInt32(GridView1.Rows[row.RowIndex].Cells[1].Text);
// somthing like
// Server.Transfer("~/Producter/Delete?id="+ id)
// OR
Response.Redirect("~/Producter/Delete?id="+ ID);
}

How to handle multiple callbacks in ASP.Net 4.0 C#? Example

I have to handle two callbacks in one page one on button event and other on List.
When button 'showDate' is clicked it display Time
and when button 'btnlookup' is clicked it show the respective value of listbox item.. below is my code HTML & .cs file
<head runat="server">
<title></title>
<script language="javascript">
function ReceiveResults(arg, context)
{
showDate.innerHTML = arg;
}
function LookUpStock() {
var lb = document.getElementById("ListBox1");
var product = lb.options[lb.selectedIndex].text;
CallServer2(product, "");
}
function ReceiveServerData(rValue) {
document.getElementById("ResultsSpan").innerHTML = rValue;
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<span id="showDate">aaa</span>
</br>
<input id="btnShowDate" type="button" value="getDate" onclick="CallServer();"/>
</div>
<div>
<asp:ListBox ID="ListBox1" Runat="server"></asp:ListBox>
<br />
<br />
<button type="btnLookUP" onclick="LookUpStock()">Look Up Stock</button>
<br />
<br />
Items in stock: <span id="ResultsSpan" runat="server"></span>
<br />
</div>
</form>
</body>
Code for .cs file
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class callback : System.Web.UI.Page, ICallbackEventHandler
{
protected String returnValue;
protected String myDate;
protected System.Collections.Specialized.ListDictionary catalog;
public String GetCallbackResult()
{
//return returnValue;
return myDate;
}
public void RaiseCallbackEvent(String eventArgument)
{
myDate = System.DateTime.Now.ToLongTimeString();
//if (catalog[eventArgument] == null)
//{
// returnValue = "-1";
//}
//else
//{
// returnValue = catalog[eventArgument].ToString();
//}
}
protected void Page_Load(object sender, EventArgs e)
{
//For Time
ClientScriptManager cSM = Page.ClientScript;
String myCBRefrence = cSM.GetCallbackEventReference(this, "arg", "ReceiveResults", "context");
cSM.RegisterClientScriptBlock(this.GetType(), "CallServer", "function CallServer(arg, context) {" + myCBRefrence + ";}", true);
//callback back for listbox
//String cbReference = Page.ClientScript.GetCallbackEventReference(this, "arg", "ReceiveServerData", "context");
//String callbackScript = "function CallServer2(arg, context){ " + cbReference + ";}";
//Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "CallServer2", callbackScript, true);
//catalog = new System.Collections.Specialized.ListDictionary();
//catalog.Add("monitor", 12);
//catalog.Add("laptop", 10);
//catalog.Add("keyboard", 23);
//catalog.Add("mouse", 17);
//ListBox1.DataSource = catalog;
//ListBox1.DataTextField = "key";
//ListBox1.DataBind();
}
}
Code which is comments is for the second callback event, Problem is in this code is that i can only raise one callback, can someone tell me what changes i need to make in code so that i can raise both callback event.
This is a piece of personal advice: do not write JavaScript in your C# code. This will get very messy and very hard to debug quickly.
If you really need to get this information, you should use an ASP.NET Web Service (a .asmx file). You can call these Web Services using JavaScript or jQuery (I prefer jQuery myself).
If I had a .asmx file like so:
[System.Web.Script.Services.ScriptService]
public class ServerTime : System.Web.Services.WebService
{
[WebMethod]
public string Get()
{
return System.DateTime.Now.ToLongTimeString();
}
}
I would call that using the following jQuery code:
$.ajax({ type: "POST", dataType: "json", contentType: "application/json; charset=utf-8",
url: "ServerTime.asmx/Get",
success: function (result) {
$("#showDate").html(result.d);
}
});
Note that success is deprecate din the latest version of jQuery, but I can't find a good example of done online.

Categories

Resources