I have a function on my server side.
protected void SelectParticipant(string CompanyId, string EmployeeNumber)
{
//I do some stuff here.
}
I want to call this function from JavaScript on the client side. I've tried searching for it, but all the suggestions I found were for calling a Page Method via AJAX. I don't want that, I want to cause a postback.
function MyJSFunction(companyid, employeenumber)
{
//cause postback and pass the companyid and employee number
//this is where I need help!
}
How can I cause a postback and run a server side function from my JavaScript?
You can solve your problem using two HiddenField.
Set the two HiddenField using js/jquery(as you prefer)
Force the form submit in the js function(form1.submit())
In the formLoad check if the HiddenFields are empty. If no run your method and then clear the HiddenFields
You can use the __doPostBack function to post to server. just make sure you add a server control to the page so the function is inserted. here is a small example that you can customize for your needs:
aspx:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="Try1.WebForm1" EnableEventValidation="false"%>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="Scripts/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#lblInvoke').hover(
function () {
__doPostBack('<%= LinkButton1.ClientID %>', 'value1,value2');
}
);
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<label id="lblInvoke">Hover This!</label>
<br />
<asp:LinkButton ID="LinkButton1" runat="server" OnClick="LinkButton1_Click" Style="display:none;">LinkButton</asp:LinkButton>
<asp:Label ID="Label1" runat="server" Text=""></asp:Label>
</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;
namespace Try1
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void LinkButton1_Click(object sender, EventArgs e)
{
string passedArgument = Request.Params.Get("__EVENTARGUMENT");
string[] paramsArray = passedArgument.Split(',');
Label1.Text = string.Format("Returned from server. params: {0},{1}", paramsArray[0], paramsArray[1]);
}
}
}
Make sure you add the EnableEventValidation="false" attribute to page.
Here's how I did it...
<script type="text/javascript">
function AddParticipant(companyid, employeenumber)
{
$("#AddParticipantPanel").dialog("close");
var myargs = {CompanyId: companyid, EmployeeNumber: employeenumber};
var myargs_json = JSON.stringify(myargs);
__doPostBack('<%= SelectParticipantBtn.UniqueID %>', myargs_json);
}
</script>
<asp:Button runat="server" ID="SelectParticipantBtn" ClientIDMode="Static" OnClick="SelectParticipantBtn_Click" style="display:none;" />
And on the server side...
/* this is an inner class */
public class SelectParticipantEventArgs
{
public string CompanyId {get; set;}
public string EmployeeNumber {get; set;}
}
protected void SelectParticipantBtn_Click(object sender, EventArgs e)
{
string args = Request.Form["__EVENTARGUMENT"];
var myargs = JsonConvert.DeserializeObject<SelectParticipantEventArgs>(args);
string emp_no = myargs.EmployeeNumber;
string company_id = myargs.CompanyId;
//do stuff with my arguments
}
Instead of using HiddenFields, I used a hidden button. This model works better because I can go directly to the button's event handler instead of having to add code to the Page_Load function.
Related
iam writing code for button onclient event with js to print the webpage and onclick event for generating pdf and downloading it ..both must be done in a single action..
but when i cancel print which i onclient click event then oncick event is firing .
<script type="text/javascript">
function PrintPage()
{
window.print();
return true;
}
<asp:Button ID="Button3" runat="server" Text="PTPDF" UseSubmitBehavior="false" OnClick="Button3_Click1" OnClientClick ="javascript:PrintPage();" />
</div>
protected void Button3_Click1(object sender, EventArgs e)
{//here is the code for pdf generation,
this code must get fired automatically after onclient click event without users action}
Below code works perfectly on my end and illustrateson how both OnClick and OnClientClick works at a same time-
ASPX -
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Click.aspx.cs" Inherits="Click" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script language="javascript" type="text/javascript">
function confirmthis()
{
document.getElementById('TextBox2').value = 'onclient works';
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" OnClientClick="return confirmthis();" Text="Click Me" /></div>
</div>
</form>
</body>
</html>
Inline code -
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Click : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
TextBox1.Text = "OnClick works";
}
}
Please paste the above code at your end and let me know if it still doesn't work.
Thanks!!
Before I start - I know how the postback works, I know that page will update only when it is fully rendered, I just want to make sure, that there is no solution for my case to make minor updates to page.
Problem definition. I have ASP.NET project and a WCF service. WCF service contains few functions which return some string as result (e.g. was there mistake or did it go well). On the ASP.NET website I have a button, which fires sequence of actions. These actions are calls of functions from the WCF service. With usual postback (it is called ones I press the button), page will reload only when results for all functions are received as it should be (it takes quite much time). All results are added to a textbox.
Question. Is there any way really to add a result to the textbox asynchronously? I mean, really, using AJAX/something else, I do not care. I can not believe that this problem is unsolved in the ASP.NET. I just need a user to see progress - results of fired functions before the whole sequence is fired.
I spent few hours and I did not find any clue except UpdatePanel but I could not use it to solve the case. Do you have any ideas?
protected void Button1_Click(object sender, EventArgs e)
{
textBox1.text += wcf.function1();
textBox1.text += wcf.function2();
textBox1.text += wcf.function3();
//only now the page updates.
}
Demo using ajax and generic handlers. This example was made in MonoDevelop but you can pass to Visual Studio without changing the code.
The folders and files:
/*
DemoGenericHandler
|
|---Default.aspx
|---Default.aspx.cs
|
|---GenericHandlers
| |
| |---MyHandler.ashx
| |---MyHandler.ashx.cs
|
|---web.config
*/
This is the code for Default.aspx
<%# Page Language="C#" Inherits="DemoGenericHandler.Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head runat="server">
<title>Default</title>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var $button1 = $("#<%= Button1.ClientID %>");
var $txt1 = $("#<%= textBox1.ClientID %>");
var $txt2 = $("#<%= textBox2.ClientID %>");
var $txt3 = $("#<%= textBox3.ClientID %>");
var $progressBar = $("#progressBar");
$button1.click(function(e){
//avoid postback
e.preventDefault();
//show progress bar
$progressBar.fadeIn('fast');
//ajax-post
$.post("<%= ResolveClientUrl("~/") %>GenericHandlers/MyHandler.ashx",
{data:"requestFromDefaultPage"},
function(jsonInstance){
if(jsonInstance)
{
$txt1.val(jsonInstance.Value1);
$txt2.val(jsonInstance.Value2);
$txt3.val(jsonInstance.Value3);
}
//hide progressbar
$progressBar.fadeOut('fast');
});//ajax-post
});//click
});
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:Button id="Button1" runat="server" Text="Call Ajax!" OnClick="Button1_Click" />
<img src="http://casa-vivebien.com/contents/media/progressbar.gif" id="progressBar" title="" style="display:none;" />
<br />
<asp:TextBox ID="textBox1" runat="server"></asp:TextBox>
<asp:TextBox ID="textBox2" runat="server"></asp:TextBox>
<asp:TextBox ID="textBox3" runat="server"></asp:TextBox>
</form>
</body>
</html>
This is the code-behind:
using System;
using System.Web;
using System.Web.UI;
namespace DemoGenericHandler
{
public partial class Default : System.Web.UI.Page
{
protected void Button1_Click(object sender, EventArgs e)
{
//textBox1.Text += wcf.function1();
//textBox1.Text += wcf.function2();
//textBox1.Text += wcf.function3();
//only now the page updates.
}
}
}
Code behind of the generic handler (*.ashx.cs):
using System;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Threading;
namespace DemoGenericHandler
{
public class MyHandler : System.Web.IHttpHandler
{
public virtual bool IsReusable {
get {
return false;
}
}
public virtual void ProcessRequest (HttpContext context)
{
//if you need get the value sent from client (ajax-post)
//string valueSendByClient = context.Request.Form["data"] ?? string.Empty;
//you must use a library like JSON.NET (newtonsoft) to serialize an object
//here for simplicity i'll build the json object in a string variable:
string jsonObj = "{\"Value1\": \"1\",\"Value2\": \"2\",\"Value3\": \"3\"}";
//await 5 seconds: (imitates the time that your wcf services take)
Thread.Sleep(5000);
//send the result to the client
context.Response.ContentType = "text/json";
context.Response.Write(jsonObj);
}
}
}
A capture:
My aspx page
<span>
<asp:UpdatePanel ID="upPlayBtn" runat="server" >
<ContentTemplate>
<asp:Button runat="server" id="btn" Text="Play" OnClick="btnPlay" />
</ContentTemplate>
</asp:UpdatePanel>
</span>
<script type="text/javascript">
function OpenPlayerWindow() {
OpenPlayWindow("<%=PlayLink%>");
}
function OpenPlayerWindowForError() {
alert("Please check after sometime. Thanks!")
}
</script>
My CS page
protected void btnPlay(object sender, EventArgs e)
{
if(condition)
ScriptManager.RegisterStartupScript(upPlayBtn, upPlayBtn.GetType(),"tabs", "OpenPlayerWindow();", true);
}
else
{
ScriptManager.RegisterStartupScript(upPlayBtn, upPlayBtn.GetType(), "tabs", "OpenPlayerWindowForError();", true);
}
}
When I click the "Play" button for first time, OpenPlayerWindow() or OpenPlayerWindowForError() opens accoding to the condition. And if I click the button again, "btnPlay" is called but not any of JS function.
If I refresh the page, it works perfect again.
<span>
<asp:UpdatePanel ID="upPlayBtn" runat="server" >
<ContentTemplate>
<asp:Button runat="server" id="btn" Text="Play" OnClick="btnPlay" />
<script type="text/javascript">
function OpenPlayerWindow() {
OpenPlayWindow("<%=PlayLink%>");
}
function OpenPlayerWindowForError() {
alert("Please check after sometime. Thanks!")
}
</script>
</ContentTemplate>
</asp:UpdatePanel>
</span>
I am not able to write this code in comments hence I am writing this as an answer. The following is the code which I have with me. Please copy-paste it in a separate project and try if it works.
Also if I am not replicating this issue properly(not written the code correctly) then please comment.
If the code is okay with you and if it works on a separate project then there probably is a problem in some other code which is not shown in your question.
aspx
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm2.aspx.cs" Inherits="Practice_Web.WebForm2" %>
<!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></title>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" EnablePageMethods="true" runat="server">
</asp:ScriptManager>
<div>
<span>
<asp:UpdatePanel ID="upPlayBtn" runat="server">
<ContentTemplate>
<asp:Button runat="server" ID="btn" Text="Play" OnClick="btnPlay" />
</ContentTemplate>
</asp:UpdatePanel>
</span>
<%--It works if I keep the script here also--%>
</div>
</form>
</body>
<script type="text/javascript">
function OpenPlayerWindow() {
alert("Thanks!");
}
function OpenPlayerWindowForError() {
alert("Please check after sometime. Thanks!");
}
</script>
</html>
aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Practice_Web
{
public partial class WebForm2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//This is just to simulate the condition part of the original code
if (Session["condition"] == null)
Session["condition"] = false;
else
Session["condition"] = !Convert.ToBoolean(Session["condition"]);
}
protected void btnPlay(object sender, EventArgs e)
{
bool condition = Convert.ToBoolean(Session["condition"]);
if (condition)
{
ScriptManager.RegisterStartupScript(upPlayBtn, upPlayBtn.GetType(), "tabs", "OpenPlayerWindow();", true);
}
else
{
ScriptManager.RegisterStartupScript(upPlayBtn, upPlayBtn.GetType(), "tabs", "OpenPlayerWindowForError();", true);
}
}
}
}
try below code
protected void btnPlay(object sender, EventArgs e)
{
if(condition)
ScriptManager.RegisterStartupScript(this, GetType(),"tabs", "OpenPlayerWindow();", true);
}
else
{
ScriptManager.RegisterStartupScript(this, GetType(), "tabs", "OpenPlayerWindowForError();", true);
}
}
I am adding a new attribute to a DataList control in asp.net. I want to set the attribute on the server in C#. I then want to modify it in jQuery on the client, and get the new value of the attribute in C# back on the server. I think if I initialize the attribute to say "0" in my .aspx code, it get reset to "0" during the postback.
So, I'm using DataList.Attributes.Add() to create and init the attribute value during my render. On the client, I use .attr in jQuery to modify the value. During the postback on the server, I use DataList.Attributes["attributeName"] to get the new value, but it's null. I've changed EnableViewState for the DataList, its parent, and grandparent to true and false, but I still get a null value.
Is there a way to create and init an attribute on the server, modify it in jQuery on the client, and get the new value in C# back on the server?
A server control's attributes are persisted in the page viewstate. On postback the server control is re-created, and, its attribute values are re-created by parsing the viewstate value, from the posted data.
Hence any attempt to modify a server-created-control-attribute, or, add an attribute on a server-control from the client will not work. (More precisely it won't be very straight forward even if it might be possible).
Anyhow, a browser is "programmed" to send (over the wire) data held inside any html input or select control (hope I didn't miss anything) nested inside the html form. Further, all such controls need to be identified by the value specified by the name attribute. For e.g.
<form method="post" action="default.aspx">
<input type="text" name="foo" value="123"/>
<input type="submit" value="submit to server"/>
</form>
If one such form is submitted to a server like ASP.NET (which is an abstraction of IIS which implements the CGI standard), you can get the value of the textbox by doing something like:
string fooValue = Request.Form["foo"];
A browser program is usually programmed to send data corresponding the name and value attributes only.
Now, since you are looking at getting more than one kind of data on the server, but still associated with a single control, your options are to go with any of the following:
Access the value from two separate controls on the server. However, its your job to figure their are associations.
You can think of a user control approach, which ultimately is like the above but if written will give you a neat encapsulation.
Here is a small example of the 2nd approach:
CompositeControl.ascx:
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="CompositeControl.ascx.cs" Inherits="WebApp.Attributes.CompositeControl" %>
<label>Enter Name</label>
<asp:TextBox runat="server" ID="tbxName"></asp:TextBox>
<asp:HiddenField ID="hdnAge" runat="server" />
CompositeControl.ascx.cs:
using System;
namespace WebApp.Attributes
{
public partial class CompositeControl : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
if (!string.IsNullOrEmpty(this.HiddenFieldClientId))
{
hdnAge.ClientIDMode = System.Web.UI.ClientIDMode.Static;
hdnAge.ID = this.HiddenFieldClientId;
}
}
public string Name
{
get
{
return tbxName.Text;
}
set
{
tbxName.Text = value;
}
}
public int Age
{
get
{
return int.Parse(hdnAge.Value);
}
set
{
hdnAge.Value = value.ToString();
}
}
public string HiddenFieldClientId { get; set; }
}
}
default.aspx:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="default.aspx.cs" Inherits="WebApp.Attributes._default" %>
<%# Register src="CompositeControl.ascx" tagname="CompositeControl" tagprefix="uc1" %>
<!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></title>
<script src="Scripts/jquery-2.1.0.min.js"></script>
<script>
$(function () {
$('#tbxAge').val($('#personAge').val());
$('#btnSetAge').click(function () {
$('#personAge').val($('#tbxAge').val());
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<uc1:CompositeControl ID="CompositeControl1" runat="server" HiddenFieldClientId="personAge" />
<br />
<input id="tbxAge" type="text" />
<input id="btnSetAge" type="button" value="Set" />
<p>Hit <strong>set</strong> before clicking on submit to reflect age</p>
<asp:Button runat="server" ID="btnSubmit" Text="Submit"
onclick="btnSubmit_Click" />
<br />
<asp:Literal runat="server" ID="ltrlResult"></asp:Literal>
</div>
</form>
</body>
</html>
default.aspx.cs:
using System;
namespace WebApp.Attributes
{
public partial class _default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
CompositeControl1.Age = 23;
CompositeControl1.Name = "Default";
}
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
ltrlResult.Text = string.Format("<p>{0}</p><p>{1}</p>", CompositeControl1.Name, CompositeControl1.Age);
}
}
}
You could make an AJAX call in wich you send the changes made it with jquery to some webservices method in your code behind to handle it.
AJAX jquery post change call:
$.ajax({
type: 'POST',
url: 'Default.aspx/Checksomething',
data: '{"userValuePostChanged ": "' + DtLValue+ '"}',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function(msg) {
alert("Result: " + msg);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Error: " + textStatus);
}
});
webservices C#
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public Checksomething(string userValuePostChanged)
{
//Do some stuff with userValuePostChanged
return "something else"
}
This are the links where I took the examples:
consume .net web service using jquery
How to use jQuery to make a call to c# webservice to get return value
http://www.codeproject.com/Articles/66432/Consuming-Webservice-using-JQuery-ASP-NET-Applicat
I have GUI for data acceptance.
I need to pass all the parameters of the form on click of a submit button to a function declared in C#.
Please help.
Using .Net us have too types of submit tags, one starting with <asp: and the other starting with <input. the <input html tag can call javascript and if you add the runat="server" attribute, you will enable it to also have C# code behind the button.
First of all, you will need to create an aspx page (say submission.aspx) that will receive the POST submission of your form. In that page, you can include your .cs file that contains the method/function you want to pass the data to.
Next, you want to submit you submit your data to submission.aspx. To do that, you will need to have a form which will submit its data to submission.aspx.
<form action='submission.aspx' method='POST' id='data-submission'>
<!-- stuff here -->
</form>
If you want to perform ajax submission, you can use jquery and use this code:
$('#data-submission').submit(function(evt){
var $form = $(this);
var url = $form.attr('action');
$.post(url, $form.serialize(), function(){alert('submission complete!);});
});
I wonder if all that helped you.
PS: I haven't used .NET for web programming in a long time now.. but what I've written here in this answer hold universally true for any web programming language/framework.
If your using asp.net you just need to double click the button(if it is an asp button) and it should make a click event.
In the click event you could get your other controls like
default.aspx 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></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</div>
</form>
</body>
</html>
Codebehind
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
// you can declare it as a field variable so the entire code behind can use it
private Passengerdetails myClass;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
// create an instance of the class.
myClass = new Passengerdetails ();
// stick textbox1 contents in the property called test.
myClass.PassengerName = TextBox1.Text;
int a = Convert.ToInt32(TextBox1.Text);
int b = Convert.ToInt32(TextBox2.Text);
int sum = Add(a, b);
// do something with it like return it to a lbl.
Label1.Text = sum.ToString();
}
private int Add(int a, int b)
{
return a + b;
}
}
Edit. You just make a class.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
/// <summary>
/// Summary description for passengerdetails
/// </summary>
public class Passengerdetails
{
public Passengerdetails ()
{
public string PassengerName{ get; set; }
}
}