Thursday 31 August 2017

Return value from JavaScript to codebehind in asp.net.

Can i get value from javascript in C# code behind
Description:

In this example we explain that how to return value from JavaScript function to code behind using C# in asp.net.or how to get the value from JavaScript function to code behind in asp.net using C#.or how to use JavaScript function return value in code behind in asp.net using C#.

Here we demonstrate that how to return JavaScript function value to code behind of asp.net using hidden field element using C#.or Can i get value from javascript in C# code behind.

Aspx:


<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="test.aspx.cs" Inherits="Dashboard.test" %>

<!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>
    <title>ASP.Net: Get Return Value from JavaScript function in Code Behind using C# and
        VB.Net</title>
    <script type="text/javascript">
        function Confirm() {
            var confirm_value = document.createElement("INPUT");
            confirm_value.type = "hidden";
            confirm_value.name = "confirm_value";
            if (confirm("Are you sure to do this operation?")) {
                confirm_value.value = "Yes";
            } else {
                confirm_value.value = "No";
            }
            document.forms[0].appendChild(confirm_value);
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <asp:Button ID="btnConfirm" runat="server" OnClick="OnConfirm" Text="Raise Confirm"
        OnClientClick="Confirm()" />
    </form>
</body>
</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 Dashboard
{
    public partial class test : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }
        public void OnConfirm(object sender, EventArgs e)
        {
            string confirmValue = Request.Form["confirm_value"];
            if (confirmValue == "Yes")
            {
                //Here you can perform your operation
                this.Page.ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('You clicked YES!')", true);
            }
            else
            {
                this.Page.ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('You clicked NO!')", true);
            }
        }
    }
}



0 comments:

Post a Comment