Solved

Post parameters

Posted on 2011-09-18
16
301 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
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
Turn Insights Into Action

You’ve already invested in ITSM tools, chat applications, automation utilities, and more. Fortify these solutions with intelligent communications so you can drive business processes forward.

With xMatters, you'll never miss a beat.

 
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
 

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

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Performance in games development is paramount: every microsecond counts to be able to do everything in less than 33ms (aiming at 16ms). C# foreach statement is one of the worst performance killers, and here I explain why.
Today, the web development industry is booming, and many people consider it to be their vocation. The question you may be asking yourself is – how do I become a web developer?
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
HTML5 has deprecated a few of the older ways of showing media as well as offering up a new way to create games and animations. Audio, video, and canvas are just a few of the adjustments made between XHTML and HTML5. As we learned in our last micr…

719 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