Solved

Post parameters

Posted on 2011-09-18
16
293 Views
Last Modified: 2012-08-13
Please let me know how I can POST parameters through my ASP.NET webpage (C#).
Also, I want to retrieve the POST parameters from my JavaScript code.

If possible, please provide some sample code. Thanks!
0
Comment
Question by:dshrenik
16 Comments
 
LVL 16

Expert Comment

by:disrupt
ID: 36555716
0
 

Author Comment

by:dshrenik
ID: 36555894
Can you tell me how one ASP.NET webpage can redirect to another ASP.NET webpage, and at the same time pass parameters (POST), so that the JavaScript code in the second page can retrieve the POST parameters?

Thanks!
0
 
LVL 15

Expert Comment

by:navneethegde
ID: 36555993
Hi!

Could you also check this along with the disrupts'  link
http://aspdotnetfaq.com/Faq/How-to-make-Cross-Page-Postback-in-ASP-Net.aspx

Thanks!

0
 
LVL 3

Expert Comment

by:ExpertLogin_890
ID: 36559214

you can pass the post parameter by form collection by adding hidden fileds or any controls you have used on form you can retrieve its values by using
Request.Form ("lastname")
in javascript you can use the

var lastname = '<%=Request.Form("Lastname")%> ' ;
0
 

Author Comment

by:dshrenik
ID: 36564071
The problem is that I need to construct the POST parameters with C# code. They're not values of form elements.
0
 
LVL 16

Expert Comment

by:disrupt
ID: 36564966
you can use querystring take a look at this example it redirects as well and shows how to retrieve in both C# & javascript:

http://triaslama.wordpress.com/2008/04/12/retrieving-query-string-values-in-aspnet-and-javascript/
0
 

Author Comment

by:dshrenik
ID: 36565030
I want to do POST, not GET. Thanks!
0
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 
LVL 16

Expert Comment

by:disrupt
ID: 36565050
0
 

Author Comment

by:dshrenik
ID: 36565057
I want to do this when the user clicks an image button on my .aspx page. There are several image buttons, and depending on the button clicked, I want to POST parameters and redirect to a particular page.
0
 
LVL 16

Expert Comment

by:disrupt
ID: 36593250
I would set something like so for your ImageButtons:

        protected void ImageButton_Click(object sender, ImageClickEventArgs e)
        {
            postData(TextBox1.Text, TextBox2.Text, TextBox3.Text);

        }

        protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
        {
            postData(TextBox4.Text, TextBox5.Text, TextBox6.Text);

        }
,,,,,

on each one of your button's (onclick event for each)

and the following method for postData like so:

so you can pass different data depending in your image button

protected void postData(string a, string b, string c)
        {

            string url = "URL YOU WANT TO POST TO";

            StringBuilder postData = new StringBuilder();

            postData.Append("POSTPARAM1=" + HttpUtility.UrlEncode(a) + "&");
            postData.Append("POSTPARAM2=" + HttpUtility.UrlEncode(b) + "&");
            postData.Append("POSTPARAM3=" + HttpUtility.UrlEncode(c) + "&");
 
            StreamWriter writer = null;

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = postData.ToString().Length;
            try
            {
                writer = new StreamWriter(request.GetRequestStream());
                writer.Write(postData.ToString());

                HttpWebResponse WebResp = (HttpWebResponse)request.GetResponse();

                Stream Answer = WebResp.GetResponseStream();
                StreamReader _Answer = new StreamReader(Answer);
                Console.WriteLine(_Answer.ReadToEnd());

            }
            finally
            {
                if (writer != null)
                    writer.Close();
            }
        }

Open in new window

0
 
LVL 16

Expert Comment

by:disrupt
ID: 36593254
Also to redirect to a page simply use:

Response.Redirect("newpage.aspx", true);
0
 

Author Comment

by:dshrenik
ID: 36593309
Can these parameters be retrieved from javascript on "newpage.aspx"? Thanks!
0
 

Author Comment

by:dshrenik
ID: 36593311
And url in my C# code must be set to "newpage.aspx" right?
0
 
LVL 16

Accepted Solution

by:
disrupt earned 500 total points
ID: 36596997
Full working example, you shouldn't need to retrieve it in javascript in my example below I showed you how to pass the values into javascript. Also side note make sure you have the correct domain/local host present here:

string url = "http://localhost:31544/newpage.aspx";

(IN DEFAULT.ASPX CODEBEHIND)
DEFAULT.ASPX:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="default.aspx.cs" Inherits="WebApplication30._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">
        <asp:ImageButton ID="ImageButton1" runat="server" OnClick="ImageButton_Click" />
    </form>
</body>
</html>

DEFAULT.ASPX CODEBEHIND:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using System.IO;
using System.Net;

namespace WebApplication30
{
    public partial class _default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void ImageButton_Click(object sender, ImageClickEventArgs e)
        {
            postData("AAA", "BBB", "CCC");

        }

        protected void postData(string a, string b, string c)
        {

            string url = "http://localhost:31544/newpage.aspx";

            StringBuilder postData = new StringBuilder();

            postData.Append("POSTPARAM1=" + HttpUtility.UrlEncode(a) + "&");
            postData.Append("POSTPARAM2=" + HttpUtility.UrlEncode(b) + "&");
            postData.Append("POSTPARAM3=" + HttpUtility.UrlEncode(c) + "&");

            StreamWriter writer = null;

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = postData.ToString().Length;
            try
            {

                writer = new StreamWriter(request.GetRequestStream());
                writer.Write(postData.ToString());
                writer.Close();

                HttpWebResponse WebResp = (HttpWebResponse)request.GetResponse();

                Stream Answer = WebResp.GetResponseStream();
                StreamReader _Answer = new StreamReader(Answer);
                Response.Write(_Answer.ReadToEnd());

            }
            finally
            {
                if (writer != null)
                    writer.Close();
            }
        }
    }
}

NEWPAGE.ASPX

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

<!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" runat="server"></asp:scriptmanager>
    <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
    </form>
</body>
</html>

NEWPAGE.ASPX CODEBEHIND:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebApplication30
{
    public partial class newpage : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string param1 = "", name1 = "";
            string param2 = "", name2 = "";
            string param3 = "", name3 = "";

            System.Text.StringBuilder displayValues =
        new System.Text.StringBuilder();
            System.Collections.Specialized.NameValueCollection
                postedValues = Request.Form;
            String nextKey;
            for (int i = 0; i < postedValues.AllKeys.Length - 1; i++)
            {
                nextKey = postedValues.AllKeys[i];


                displayValues.Append(nextKey);
                displayValues.Append(" = ");
                displayValues.Append(postedValues[i]);
                displayValues.Append("<br>");

                if (nextKey == "POSTPARAM1")
                {
                    name1 = nextKey;
                    param1 = postedValues[i];
                }
                else if (nextKey == "POSTPARAM2")
                {
                    name2 = nextKey;
                    param2 = postedValues[i];
                }
                else if (nextKey == "POSTPARAM3")
                {
                    name3 = nextKey;
                    param3 = postedValues[i];
                }
            }
            Label1.Text = displayValues.ToString();

            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "Script1", "alert('Parameters: " + name1 + " " + param1 + "');", true);
            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "Script2", "alert('Parameters: " + name2 + " " + param2 + "');", true);
            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "Script3", "alert('Parameters: " + name3 + " " + param3 + "');", true);
        }
    }
}

Open in new window

0

Featured Post

Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

Join & Write a Comment

Browsers only know CSS so your awesome SASS code needs to be translated into normal CSS. Here I'll try to explain what you should aim for in order to take full advantage of SASS.
Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…
Viewers will learn about if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:

706 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now