Querystring encoding issue - c#

I am facing one problem while storing a querystring value in a variable.
My url is something like shown below:
http://localhost:1372/testapp/default.aspx?Search=%family%
Below is what I tried:
string result = Request.QueryString["Search"].ToString();
When I tried to save the querystring search in variable its taking value as �mily% .
How can I get value of search parameter as family?
Thanks in advance.

The query string parameters have to get URL-encoded. The problem ist th % character which is used for URL encoding, so it has to get encoded itself.
'%' becomes '%25'
Which means, the whole URL becomes:
http://localhost:1372/testapp/default.aspx?Search=%25family%25
your can use HttpUtitlity.UrlEncode

In Parent Page Encode query string this way
public static sting Encode(string sData)
{
return HttpUtility.UrlEncode(sData);
}
Now pass this encoded query string to your parent page & on Parent page decode that query string by following function. I assume that encoded query string name is sData & its passed from parent page to child page
public static string Decode()
{
string dSData = HttpUtility.UrlDecode(Request.QueryString["sData"].ToString());
return dsData;
}
I think you have idea about how to pass query string from parent to child page
try this solution for more .

Related

Clear duplicated Query String values asp.net

I want to create and name a folder with the values from a query string. For example:
api/controller?lotid=value&operation=value
After debugging the application (as shown below) I realized that every request I tested became a collection. As a result, I suspect the folder is named (Collection)_(Collection) instead of the query string values lotid_operation.
Any idea why this happened?
This is how I get the queries in the controller file
public string Get(string lotid, string operation) {
//Secrets
}
Here I create the folder name
string folderName = lotid + "_" + operation;
and the how the AbsoluteUri looks in the debugger panel
http://localhost:5000/api/otdash?lotid=XBSs&operation=xhr1&lotid=S23B&operation=xhr1&lotid=SWB45&operation=xhr1&lotid=SWB556&operation=34s&lotid=SD23&operation=xhr1&lotid=322&operation=3sl&lotid=%27sdfa%27&operation=%27ada%27&lotid=%27SWBT12010%27&operation=%27xhr1%27&lotid=%27SWEB000%27&operation=%27xhr1&lotid=%27RESS0292%27&operation=%27das%27&lotid=SBBB&operation=sasc&lotid=%27ssss%27&operation=%27A34%27

Passing multiple variables between pages and using them

I have three variables I'm trying to pass from one page to another: Two checboxlists (just the checked values) and one DateTime.
I'm getting the checked items like this (this is just for one of these checkboxlists which is called lstUsers):
string cblvalues = "";
foreach (ListItem cbitem in lstUsers.Items)
{
if (cbitem.Selected)
{
cblvalues += cbitem.Value + "-";
}
}
cblvalues = cblvalues.Trim('-');
Response.Redirect("Results.aspx?cblvalues=" + cblvalues);
How would I pass the other checkboxlist and the DateTime to "Results.aspx" as well? I've seen a few different examples such as Server.Transfer, and I'm not sure which one is correct here.
And for using them on the Results.aspx page, would I just do:
string cblvalues = Request.QueryString["cblvalues"];
You can put as many values as you like on the query string. (Though as query strings get very long the web server would eventually impose a limit.) Here you simply append one key/value pair:
Response.Redirect("Results.aspx?cblvalues=" + cblvalues);
Just use a & to separate additional key/value pairs:
Response.Redirect("Results.aspx?cblvalues=" + cblvalues + "&moreValue=" + moreValues);
If you do get to the point where the query string becomes absurdly long and you basically have a lot of data to pass to the next page, then you'd be looking at other ways of doing this. A simple alternative may be to store the values in session state, redirect the user, then pull the values from session state. Something as simple as this:
Session["cblvalues"] = cblvalues;
Session["moreValues"] = moreValues;
Response.Redirect("Results.aspx");
Then in Results.aspx you can get the values:
var cblValues = Session["cblvalues"];
// etc.
You might also clear the session values once you get them, if the session doesn't need to keep carrying them:
Session.Remove("cblvalues");
You can pass multiple values through query string by seperated them with a &
so your snippet will be like the following:
Let cblSecond be the second combobox then;
// Building first value here
foreach (ListItem cbitem in cblSecond.Items)
{
if (cbitem.Selected)
{
cblSecondValues += cbitem.Value + "-";
}
}
Response.Redirect("Results.aspx?cblvalues=" + cblvalues + "&cblSecondValues=" + cblSecondValues);
So that you can access them separately like this:
string cblvalues = Request.QueryString["cblvalues"];// gives you the first value
string cblSecondValues= Request.QueryString["cblSecondValues"];// gives you the second value
Response.Redirect(String.Format("Results.aspx?value1={0}&value2={1}&value3={2}", Value1, Value2, Value3));
If you really want to pass them using querystring then you ahouls include them as well
Response.Redirect("Results.aspx?cblvalues=" + cblvalues + "&cblvalues1=" + cblvalues + "&datetimemy=" + datetimevalue);
Form of a query string like below
http://server_name/path/aspxfile?field1=value1&field2=value2&field3=value3..&fieldn=valuen
As other answer mentioned, there are multiple ways like using Session or cookies or as well you can expose those control values as public properties and use then in next page using Page.PreviousPage property but the restriction is that you will have to use either of Server.Transfer() or Server.Execute() method instead of Response.Redirect.

Add empty string to Parameter List for Insertion into AccessDB

I'm trying to insert data into an Access database using the System.Data.OleDb namespace and the method OleDbCommandObject.ExecuteNonQuery(), but I am receiving errors along the lines of:
The OleDbParameterCollection only accepts non-null OleDbParameter type
objects. Parameter name: value
and
Parameter ? _[#] has no default value
Most of my parameters are string objects that work fine when a value is assigned to them via a form. However, when a non-required field is left blank (ie someString = "") and the form is submitted, then the error occurs. I have looked around for answers on this site and others that mention possible solutions like:
OleDb uses ? instead of name values
Make sure the number of parameters matches the number of ?'s and that they are inserted in the right order.
Use command.Parameters.Add(new OleDbParameter("Name", OleDbType.VarChar, 50, "Column").Value = someString); or something along those lines.
Use command.Parameters.AddWithValue("parameterName", someString);
I could set the value of the string to "[space]", but then this removes the placeholder in the form, which is not ideal, and one I do not believe should be necessary. If I have to check for the empty string and add the space before adding the value to the parameter list, then I will, but I hope to avoid the extra code if possible.
Here is an example of the code I am using:
Customer.cs
public class Customer
{
[Required]
public string ContactFirstName { get; set; }
[Required]
public string ContactLastName { get; set; }
public string Email {get; set; }
public string Phone {get; set; }
public Customer()
{
this.ContactFirstName = "";
this.ContactLastName = "";
this.Email = "";
this.Phone = "";
}
}
Method used to insert data
public int InsertValues(Customer customer)
{
this.dbConn.Open(); //System.Data.OleDb.OleDbConnection
this.query = "INSERT INTO someTable (ContactFirstName, ContactLastName, Email, Phone) VALUES (?,?,?,?)";
this.dbComm = new OleDbCommand(this.query, this.dbConn); //System.Data.OleDb.OleDbCommand
//Add parameters
this.dbComm.Parameters.AddWithValue("ContactFirstName", customer.ContactFirstName);
this.dbComm.Parameters.AddWithValue("ContactLastName", customer.ContactLastName);
this.dbComm.Parameters.AddWithValue("Email", customer.Email);
this.dbComm.Parameters.AddWithValue("Phone", customer.Phone);
this.dbComm.ExecuteNonQuery();
//--Snip--
}
The ODBC driver I am using is a Microsoft.OleDb.ACE.12.0. Any help or information that could lead me in the right direction would be greatly appreciated.
change this
public int InsertValues(Customer customer)
{
this.dbConn.Open(); //System.Data.OleDb.OleDbConnection
this.query = "INSERT INTO someTable (ContactFirstName, ContactLastName, Email, Phone) VALUES (#ContactFirstName,#ContactLastName,#Email,#Phone)";
this.dbComm = new OleDbCommand(this.query, this.dbConn); //System.Data.OleDb.OleDbCommand
//Add parameters
this.dbComm.Parameters.AddWithValue("#ContactFirstName", customer.ContactFirstName);
this.dbComm.Parameters.AddWithValue("#ContactLastName", customer.ContactLastName);
this.dbComm.Parameters.AddWithValue("#Email", customer.Email);
this.dbComm.Parameters.AddWithValue("#Phone", customer.Phone);
this.dbComm.ExecuteNonQuery();
//--Snip--
}
I'm sure there may be other solutions to this problem, but this is one I have found through trial and error that adds a small amount of code, and which can be improved by making a method that will do this instead.
As pointed out in the OP and in Gökhan Girgin's response, the AddWithValue method should appear similar to:
OleDbCommandObject.Parameters.AddWithValue("Whatever you want here", Value);
Now, my main focus is on adding a string value to the parameter list that contains no value (i.e. in the form the user left the field blank). The string is simply blank as in "[no_space]". What appears to be happening is that upon submission of the form, this value is changed from "[no_space]" to null. Attempting to type cast the Value to a string type does not solve the problem. The solution I have found involved concatenating another blank string to the Value.
Any of the combinations below I have found work though this list is most likely not exhaustive. Make sure when adding parameters with OleDb that it is in the same order as your INSERT statement.
OleDbCommandObject.Parameters.AddWithValue("#Phone", "" + customer.Phone);
OleDbCommandObject.Parameters.AddWithValue("#Phone", customer.Phone + "");
OleDbCommandObject.Parameters.AddWithValue("#Phone", "" + customer.Phone + "");
Once again, to me it does not make sense that this needs to be done unless the value is changed to null on form submission because the string is already set to "[no_space]" in the constructor. I do not see how adding another "[no_space]" changes anything, but it was accepted and no error occurs. It will be greatly appreciated if anyone can shed light on why this works.
To others who have run into this issue, I hope this helps.

C# Jquery Reference Error is Undefined

I have a C# MVC4 application in which I am writing a JQuery function to grab some values, post to an ActionResult and then refresh a partial view. All functionality is working except for setting a new var equal to the value of a variable within one of my div elements.
The pre-existing variable is called myName and is located in a div with an id of NameDiv.
Ive tried these four versions of code and each results in: Reference Error myName is not defined.
var origname = myName;
var origname = myName.value();
var origname = myName.val();
var origname = $('#NameDiv').valueOf(myName);
When running the application and inspecting element, I see that myName is populating with the correct value.
Use:
var origname = $('#NameDiv').find('input[name="myName"]').first().val();
// console.log(origname);
This will find the element on the page with the id of "NameDiv". Then it gets the input elements on the page with the name of "myName". Then it gets the first one found. It will then get the value of it (by using .val()), and store that value in the variable origname.

passing more than one variable to another page in asp.net

I want to pass more than one variable to other web pages.
I try this code
string adi = TaskGridView.SelectedRow.Cells[3].Text;
string soyadi = TaskGridView.SelectedRow.Cells[3].Text;
Response.Redirect("Default2.aspx?adi=" + adi);
Response.Redirect("Default2.aspx?soyadi=" + adi);
but it doesnt work how can I do?
The safest way is to use String.Format() with Server.UrlEncode():
Response.Redirect(String.Format("Default2.aspx?adi={0}&soyadi={1}", Server.UrlEncode(adi), Server.UrlEncode(soyadi)));
This will ensure that the querystring values will not be broken if there is an ampersand (&) for example, in the value.
Then on Default2.aspx you can access the values like:
Server.UrlDecode(Request.QueryString["adi"]);
Concatenate them like this:
Response.Redirect("Default2.aspx?adi=" + adi + "&soyadi=" + soyadi);
When passing query string parameters, use the ? symbol just after the name of the page and if you want to add more than one parameter, use the & symbol to separate them
In the consuming page:
protected void Page_Load(object sender, EventArgs e)
{
var adi = this.Request.QueryString["adi"];
var soyadi = this.Request.QueryString["soyadi"];
}
You can also use the session to pass values from one page to another
Set the values in the page where you want to pass the values from in to a session
Session["adi"] = TaskGridView.SelectedRow.Cells[3].Text;
Session["soyadi"] = TaskGridView.SelectedRow.Cells[3].Text;
In the Page where you want to retrieve- You do like this..
string adi=(string)(Session["adi"]);
string soyadi=(string)(Session["soyadi"]);
You can as well pass values through ViewState or Session the diffrent with what you doing now is: People will not see anything in your url and have no idea what happend in backend. It's good when you passing some "topsecret" data ;P

Categories