?
Solved

Post parameters

Posted on 2011-09-18
16
Medium Priority
?
303 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:Navneet
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
 [eBook] Windows Nano Server

Download this FREE eBook and learn all you need to get started with Windows Nano Server, including deployment options, remote management
and troubleshooting tips and tricks

 
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 2000 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

WordPress Tutorial 3: Plugins, Themes, and Widgets

The three most common changes you will make to your website involve the look (themes), the functionality (plugins), and modular elements (widgets).

In this article we will briefly define each again, and give you directions on how to install them.

Question has a verified solution.

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

A long time ago (May 2011), I have written an article showing you how to create a DLL using Visual Studio 2005 to be hosted in SQL Server 2005. That was valid at that time and it is still valid if you are still using these versions. You can still re…
Originally, this post was published on Monitis Blog, you can check it here . In business circles, we sometimes hear that today is the “age of the customer.” And so it is. Thanks to the enormous advances over the past few years in consumer techno…
Viewers will learn about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:
The viewer will receive an overview of the basics of CSS showing inline styles. In the head tags set up your style tags: (CODE) Reference the nav tag and set your properties.: (CODE) Set the reference for the UL element and styles for it to ensu…
Suggested Courses

770 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