On the click of a button, I call a JavaScript function. After getting the value, I need to perform some stuff from the value obtained in the code-behind. How should I call code-behind?
My aspx:
function openWindow(page) {
var getval = window.showModalDialog(page);
document.getElementById("<%= TxtInput.ClientID %>").value = getval;
//After this I need to perform stuff 'Upload(TxtInput.value)' into database from the code-behind
}
The button calling the function is set up in the following manner:
<button class="doActionButton" id="btnSelectImage" runat="server" onclick="openWindow('../rcwksheet/popups/uploader.htm')">Select Image</button>
My desired code behind (VB):
Public Sub btnSaveImage_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSelectImage.ServerClick
Dim inputFile As String = Me.TxtInput.Value
//do more stuff here
End Sub
So:
Is there a way to call code-behind from the JavaScript?
Can I somehow use the "onclick" property of a button to first go to a JavaScript and then to the code-behind?
Trigger a code-behind call "onchange" of the TxtInput.Value?
yes there is a way.
first, you can use javascript to submit the form after your return value is set in TxtInput.
function openWindow(page) {
var getval = window.showModalDialog(page);
document.getElementById("<%= TxtInput.ClientID %>").value = getval;
document.forms[0].submit();
}
then in your code behind, you can handle TxtInput's value in page load event.
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
if (this.Input.Value != string.Empty)
{
this.Input.Value += "blah";
}
}
}
note: you may need Identifying control that caused postback
You can put the server side code into a web service, make a service reference in an asp:ScriptManager on your aspx page and then you can call/execute the web service from javascript by calling:
WebServiceClassName.MethodName(javascriptvariable, doSomethingOnSuccess)
Here is a link on doing that:
http://msdn.microsoft.com/en-us/magazine/cc163499.aspx
You can call the __doPostBack Event.
function openWindow(page) {
var getval = window.showModalDialog(page);
document.getElementById("<%= TxtInput.ClientID %>").value = getval;
__doPostBack('btnSelectImage', getval);
}
And on the server side in your code behind, you can get the value:
In the PageLoad method:
if (Request.Form["__EVENTTARGET"] == "btnSelectImage")
{
//get the argument passed
string parameter = Request["__EVENTARGUMENT"];
//fire event
btnSaveImage_Click(this, new EventArgs());
}
Related
Trying to use public properties from C# code behind and want to read the variable value from a JavaScript function
JavaScript function:
function IsAgentInProgram()
{
var optStatus = "<%=AgentOptInStatus%>";
if (optStatus == "True")
alert("You are opted in!");
else
alert ("You are opted OUT");
}
C# code behind
public bool AgentOptInStatus;
private void Page_Load(object sender, System.EventArgs e)
{
this.AgentOptInStatus = true;
}
This does not work. Output comes back as You are opted OUT. I also did an alert on optStatus and it comes back with: "<%=AgentOptInStatus%>"
Am I missing something?
You cannot read the client side variables directly in the codebehind. What you can do is creating a hidden field and setting the value with javascript, then you can read it in c#.
<asp:HiddenField ID="hdnfldVariable" runat="server" />
JS:
<script type="text/javascript">
var somefunction = function () {
var hdnfldVariable = document.getElementById('hdnfldVariable');
hdnfldVariable.value = 'value from javascript';
}
</script>
c# :
string selected = hdnfldVariable.Value.ToString();
Another option is to make an HTTP request to the server to call a function from a controller passing the data as parameters.
I need to call confirmation message box from codebehind as the user select data from dropdown list and when the selected data is 1 for example a confirmation box will appear to the user to confirm his action
so I did that as below in the code behind I called this JavaScript method:
if (dropdownlist1.SelectedValue == 1)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "CallConfirmBox", "CallConfirmBox();", true);
}
The script function:
<script type="text/javascript">
function CallConfirmBox() {
if (confirm("هل تريد ان تفصل الباليت؟")) {
alert("سيتم فصل الباليت!");
PageMethods.getdata(onSuccess, onError);
function onSuccess() {
alert(data);
}
function onError() {
alert(errorMessage);
}
}
} else {
//CANCEL – Do your stuff or call any callback method here..
alert("done!");
}
}
And I've added the below line at the beginning of the HTML code:
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true"> </asp:ScriptManager>
and Here is the code behind function that is called from script :
[System.Web.Services.WebMethod()]
[System.Web.Script.Services.ScriptMethod()]
public static void getdata()
{
int nRowsCheck = cMDP.Update_Segregation_PalletPart(nPalletNo);
if (nRowsCheck != 0)
{
nRowsCheck = 0;
nRowsCheck = cMDP.Update_Segregation_Pallet(nPalletNo, nUserID);
if (nRowsCheck != 0)
{
nRowsCheck = 0;
nRowsCheck = cMDP.Delete_Segregation_PalletPart_Delete(nPalletNo);
if (nRowsCheck != 0)
{
nRowsCheck = 0;
nRowsCheck = cMDP.Delete_Segregation_Pallet_Delete(nPalletNo);
}
}
}
}
But I've got the below error:
Page Methods is undefined when run the script !!
Please help as I need some support
First, you'll have to remove one } before the else in your JavaScript.
Change in your code-behind:
if (dropdownlist1.SelectedValue == "1")
For the main problem: Page Methods is undefined:
It seems from your comment that you're using a User Control (ascx). Page Methods cannot be used in a User Control. Please refer to these questions:
PageMethods is not defined
ASP.NET AJAX Page Methods from UserControl
The easiest solution is to use an aspx WebForm instead of an ascx User Control. That's what I've tested and worked.
Or you can use a WebService, as specified in the following question:
Alternate way to use page method inside user control asp.net
But the link to the sample is not working anymore.
Or you can try to use this project that tries to bring ASP.NET AJAX Page Methods to UserControls:
Control Methods for ASP.NET AJAX
You have two problems:
Change you javascript code:
PageMethods.getdata(onSuccess, onError);
function onSuccess(data)
{
alert(data);
}
function onError(data)
{
alert(data);
}
And you code behind getdata method must be a public static string function:
[System.Web.Services.WebMethod()]
[System.Web.Script.Services.ScriptMethod()]
public static string getdata()
{
//Do some things
return " Operations done successfully!";
}
since i didn´t find any solution that helped me, i thought i asked.
I need a JavaScriptfunction with calls a method in my code-behind, and since i´m really new to this, i dont understand what am i doing wrong.
On my Master Page (Site.Master) i enabled PageMethods:
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true" />
And in the Content of my Page i have put the Script:
function reply_click(clicked_id) {
alert(clicked_id);
PageMethods.javascriptTest(clicked_id);
And now my method in the code-behind:
[WebMethod]
public void javascriptTest(int buttonID)
{
Test2.Text += buttonID + "***";
// Use the ID for DB access
}
I need that ID for later, when i have to do stuff in my database, but i´m always getting PageMethods undefined errors and i dont know why :/
EDIT: The Solution was indeed to make the WebMethod static, i just made a workaround, so i could use all the details i need for my db access
JavaScript:
function reply_click(clicked_id, clicked_name) {
// Schulungsdaten holen
var grid = document.getElementById("<%= SignGridView.ClientID %>");
var row = grid.rows[0];
var appointmentData = row.cells[clicked_id].innerText;
// Userdaten holen
var userID = document.getElementById("<%= UserData.ClientID %>").innerText;
PageMethods.javaScriptUserSignIn(appointmentData, userID, clicked_name, OnSucceeded, OnFailed);
location.reload();
}
function OnSucceeded(response) {
alert(response);
}
function OnFailed(error) {
alert(error);
}
Code-Behind:
[WebMethod]
public static string javaScriptUserSignIn(string appointmentData, string userID, string status)
{
string result = "";
SignIn sign = new SignIn();
result = sign.SignToTraining(appointmentData, userID, status);
return result;
}
Your javascriptTest method needs to be static
Try This:
[System.Web.Services.WebMethod]
public static void javascriptTest(int buttonID)
{
Test2.Text += buttonID + "***";
// Use the ID for DB access
}
I have a Winforms form with a WebBrowser control on it.
I've already figured out how to connect the C# code to the Javascript in the Web Browser control by attaching an instance of a C# class to the ObjectForScripting property, like this:
public partial class Browser : Form
{
private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
webBrowser1.ObjectForScripting = new ScriptInterface();
}
}
[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
[ComVisible(true)]
public class ScriptInterface
{
public void DoSomething(string data)
{
// Do something interesting with data here
}
}
... and then call it from the Javascript like this:
<button onclick=window.external.DoSomething('with this')/>
What I haven't figured out yet is how to capture the result of a POST operation from a form in the WebBrowser control, and use it in my C# code.
You could perhaps use jQuery post instead of a form post.
Assuming your form has an id of myForm:
$( "#myForm" ).submit(function( event ) {
// Stop form from submitting normally
event.preventDefault();
// Get some values from elements on the page:
var $form = $(this),
var term = $form.find("input[name='s']").val(),
var url = $form.attr("action");
// Send the data using post
var posting = $.post( url, { s: term } )
.done(function(data) {
//Pass the response back to your code
window.external.DoSomething(data);
});
});
I have a function in server side which fills a dropdownlist. I call this function with a button click on client side using PageMethods in Javascript like this:
<asp:ScriptManager ID="smMain" runat="server" EnablePageMethods="true" />
<asp:Button runat="server" ID="SearchButton" Text="Search" OnClientClick="SearchButtonClick();return false;"/>
<asp:DropDownList runat="server" ID="SearchCityDropDownList" Width="100px"/>
And
function SearchButtonClick() {
PageMethods.SearchSearchButtonActivity(onSucess, onError);
}
function onSucess(result) {
alert(result);
}
function onError(result) {
alert('Cannot process your request at the moment, please try later.');
}
Server side function:
[WebMethod]
public static string SearchButtonActivity()
{
string result = "Everything is OK!";
foreach (string value in getCityList())
{
SearchCityDropDownList.Items.Add(new ListItem(value));
}
return result;
}
When I run this code and click on the button it just shows the "Everything is OK!" alert and
dropdownlist still empty.
Please help me to solve this problem, I think this is a post back problem because when I debug the code, items of dropdownlist are full but they don't show up in the dropdown.
Thank you
This will not work, how you have it setup. You could do an update panel, but that would be overkill, IMO. The problem is that you are making an AJAX call which just goes back to the server and returns to the client. The page, and thus the control, never get back to the server to get re-rendered.
Instead, you need to bind the result from your onsuccess callback to your dropdown list. So your web method needs to change:
[WebMethod]
public static string SearchButtonActivity()
{
var result = new List<string>();
foreach (string value in getCityList())
{
result.Add(value);
}
return result;
}
And then your onSuccess client side callback needs to handle it:
function SearchButtonClick() {
PageMethods.SearchSearchButtonActivity(onSucess, onError);
}
function onSucess(result) {
SearchCityDropDownList.options.length = 0;
for (var i==0;i<result.length;i++) {
AddOption(result[i], i);
}
}
function onError(result) {
alert('Cannot process your request at the moment, please try later.');
}
function AddOption(text, value) {
var option = document.createElement('option');
option.value = value;
option.innerHTML = text;
SearchCityDropDownList.options.add(option);
}
You can retrieve the value selected, server side in this fashion:
string selectedVal = Request[SearchCityDropDownList.UniqueID]
Thanks to this so post for the guidance: Getting the value of a DropDownList after client side javascript modification