How to send Request.Form - c#

I'm doing something really bad with my code. I'm getting all data posted to the actual page and putting into html inputs:
private void GetPostedForm()
{
System.Text.StringBuilder displayValues = new System.Text.StringBuilder();
System.Collections.Specialized.NameValueCollection postedValues = Request.Form;
for (int i = 0; i < postedValues.AllKeys.Length; i++)
{
String nextKey = postedValues.AllKeys[i];
if (nextKey.Substring( 0, 2 ) != "__")
{
displayValues.Append( "<input type='hidden' name='" + nextKey + "' value='" + postedValues[i] + "'/>" );
}
}
hiddensPost.InnerHtml = displayValues.ToString();
}
But the html inputs in this page are useless to me. I'm putting a page between 2 older pages ("A" sent form to "B"). Now I need to send "A" to "X" and then send to "B".
The question is: How can I put the requested form into the actual form to send to the next page without doing all this mess in HTML?

You can put your steps(A,X,B) and it's visible inputs, into separate asp-panels(pnlA,pnlX,pnlB)
then simply toggle panels visibility in which state you want.the ViewState will do it for you (store controls states into one hidden field within the form to post again with inputs)
so you may post user entered data 3 times with one html form( the famous asp.net form)
another solution is here , the asp.net wizard control

If you can, just change the method to GET and pass the QueryString along from page to page.

Related

How to get a value from a javascript file to c#?

I'm using ASP.NET to make a website for a hotel and at this point to show the hotel rooms I've created a javacript file to generate div's, now I want to get the value of the room number that by clicking "learn more "transfer the value of the number of the room to the other page
I already tried to use cookies but it does not work
here's the js file that generates the div:
$(document).ready(function () {
$.get('http://localhost/quartos.php', function (data) {
var results = JSON.parse(data);
console.log(results);
for (i = 0; i < results.length; i++) {
var div = "<div class='col-sm col-md-6' height='600px' width='400px'><div class='room'><a href='' class='img d-flex justify-content-center align-items-center' style='background-image: url(images/Quartos/" + results[i].imagem + ");'></a><div class='text p-3 text-center><h3 class=' mb-3'><a href=''>Quarto " + results[i].descricao + "</a></h3 > <p><span class='price mr-20'>" + results[i].Preco_quarto + "\u20AC</span><asp:Label ID='Label1' runat='server' Text='รง aop'></asp:Label><span class='per'> por noite</span></p> <ul class='list'><li><span>Max:</span>" + results[i].Lotacao_Maxima + " Pessoas</li><li><span>Vista:</span>" + results[i].Vista + "</li></ul><hr><p class='pt-1'><button class='btn btn-primary' runat='server' onserverclick='btn_quartos'>Ver Detalhes<span class='icon-long-arrow-right'></button></span></p></div></div></div>";
document.cookie = "CookieName=" + results[i].Num_Quarto + ";";
$("#quartos").append(div);
}
});
});
and the cs of the "next" page:
protected void Page_Load(object sender, EventArgs e)
{
string num_quarto = Request.Cookies["CookieName"].Value.ToString();
}
You're overwriting the cookie to something new each time in the for loop, so the cookie is always going to hold the last result in results, despite what they select.
Although, using a cookie to pass info from one page to another isn't an ideal way to do what you want anyway.
A better way would be to make your "learn more" page able to accept a room number as a query string value.
Example: http://localhost/learnmore.php?cuarto=123
Then that looks up the room information and renders the information into the html.
In doing that, you can simplify the link in your div element to point to learmore.php?cuarto="+results[i].Num_Quarto and not have to repurpose the cookie functionality for a behavior it's not really meant for.

How to Get the HTTP Post data in C#?

I am using Mailgun API. There is a section that I need to provide a URL to them, then they are going to HTTP Post some data to me.
I provide this URL (http://test.com/MailGun/Webhook.aspx) to Mailgun, so they can Post data. I have a list of parameter names that they are sending like (recipient,domain, ip,...).
I am not sure how get that posted data in my page.
In Webhook.aspx page I tried some code as follows but all of them are empty.
lblrecipient.text= Request.Form["recipient"];
lblip.Text= Request.Params["ip"];
lbldomain.Text = Request.QueryString["domain"];
Not sure what to try to get the posted data?
This code will list out all the form variables that are being sent in a POST. This way you can see if you have the proper names of the post values.
string[] keys = Request.Form.AllKeys;
for (int i= 0; i < keys.Length; i++)
{
Response.Write(keys[i] + ": " + Request.Form[keys[i]] + "<br>");
}
This code reads the raw input stream from the HTTP request. Use this if the data isn't available in Request.Form or other model bindings or if you need access to the bytes/text as it comes.
using(var reader = new StreamReader(Request.InputStream))
content = reader.ReadToEnd();
You can simply use Request["recipient"] to "read the HTTP values sent by a client during a Web request"
To access data from the QueryString, Form, Cookies, or ServerVariables
collections, you can write Request["key"]
Source:
MSDN
Update: Summarizing conversation
In order to view the values that MailGun is posting to your site you will need to read them from the web request that MailGun is making, record them somewhere and then display them on your page.
You should have one endpoint where MailGun will send the POST values to and another page that you use to view the recorded values.
It appears that right now you have one page. So when you view this page, and you read the Request values, you are reading the values from YOUR request, not MailGun.
You are missing a step. You need to log / store the values on your server (mailgun is a client). Then you need to retrieve those values on your server (your pc with your web browser will be a client). These will be two totally different aspx files (or the same one with different parameters).
aspx page 1 (the one that mailgun has):
var val = Request.Form["recipient"];
var file = new File(filename);
file.write(val);
close(file);
aspx page 2:
var contents = "";
if (File.exists(filename))
var file = File.open(filename);
contents = file.readtoend();
file.close()
Request.write(contents);
Use this:
public void ShowAllPostBackData()
{
if (IsPostBack)
{
string[] keys = Request.Form.AllKeys;
Literal ctlAllPostbackData = new Literal();
ctlAllPostbackData.Text = "<div class='well well-lg' style='border:1px solid black;z-index:99999;position:absolute;'><h3>All postback data:</h3><br />";
for (int i = 0; i < keys.Length; i++)
{
ctlAllPostbackData.Text += "<b>" + keys[i] + "</b>: " + Request[keys[i]] + "<br />";
}
ctlAllPostbackData.Text += "</div>";
this.Controls.Add(ctlAllPostbackData);
}
}
In the web browser, open up developer console (F12 in Chrome and IE), then open network tab and watch the request and response data. Another option - use Fiddler (http://fiddler2.com/).
When you get to see the POST request as it is being sent to your page, look into query string and headers. You will see whether your data comes in query string or as form - or maybe it is not being sent to your page at all.
UPDATE: sorry, had to look at MailGun APIs first, they do not go through your browser, requests come directly from their server. You'll have to debug and examine all members of Request.Params when you get the POST from MailGun.
Try this
string[] keys = Request.Form.AllKeys;
var value = "";
for (int i= 0; i < keys.Length; i++)
{
// here you get the name eg test[0].quantity
// keys[i];
// to get the value you use
value = Request.Form[keys[i]];
}
In my case because I assigned the post data to the header, this is how I get it:
protected void Page_Load(object sender, EventArgs e){
...
postValue = Request.Headers["Key"];
This is how I attached the value and key to the POST:
var request = new NSMutableUrlRequest(url){
HttpMethod = "POST",
Headers = NSDictionary.FromObjectAndKey(FromObject(value), FromObject("key"))
};
webView.LoadRequest(request);
You can try to check the 'Request.Form.Keys'. If it will not works well, you can use 'request.inputStream' to get the soap string which will tell you all the request keys.

When user types in & rest of string dissapears

In a search text box when a user types in & the text after this is not passed to the function.
So if industry & test is typed in and submitted, only industry is passed to the function. How do i accept in the amp sound?
Text box:
Search <input type="text" id="searchtxt" /><img class ="SearchNow"src="/Content/img/search1.png"/>
Jquery to call function:
$(".SearchNow").click(function () {
var selected = $('#searchtxt').val();
if (selected != null) {
if (selected != "") {
window.location = '#Url.Action("search", "Products")?partnumber=' + selected;
}
}
});
function where text is not all coming in:
public ActionResult search(string partnumber)
{
}
Wrapped it with:
encodeURIComponent(selected)
It'll be due to & being a querystring delimiter. You'll need to escape the text before you pass it to the url:
window.location = '#Url.Action("search", "Products")?partnumber=' + encodeURIComponent(selected);
You'll need to encode the user's input in a manner suitable for passing into a URL.
So, change + selected to + encodeURI(selected) and that should do the trick.
The & is a special character in the Url and marks the next paramteter to be passed. The first parameter is marked with an ? and the following with &'s. So encode this & and it will be passed.
The & character is used a special character to separate parameters.
The posted code redirects the page to http://tld.invalid/searchAction?partnumber=industry%20&%20test
which has two parameters:
partnumber="industry "
and
test= ""
You need to encode the parameters to pass it to the server properly.
var selected = encodeURIComponent( $('#searchtxt').val() );
window.location = '#Url.Action("search", "Products")?partnumber=' + selected;
which should redirect the user to http://tld.invalid/searchAction?partnumber=industry%20%26%20test

WatIn Add a new option to a Selectlist?

I need to add a new option to a selectList in one of my unit tests, and I can't figure out how to do it.
The Dropdown currently has 2 options, I want to add a third, and use it.
I tried to use JavaScript injection using http://stevenharman.net/blog/archive/2007/07/10/add-option-elements-to-a-select-list-with-javascript.aspx as a base, but that failed. I get exceptions that crash the IE browser every time, and the text "RunScript failed" gets printed into my logs even though I don't use that text in my error output.
Is this possible in Watin? Or has Open Source Failed me?
Using the code in the link you provided, with one small change I've gotten it to work.
My changes
Changed the ID to the ID of my dropdown (of course!)
Changed the $ in the element get to 'document.getElementById'. With the $ in there instead I don't see any obvious errors or anything like that; just no action taken.
The 'New Option' is added to the dropdown as the last item and it is the selected item.
string js = "";
js = js + "var theSelectList = document.getElementById('myDropDownID'); ";
js = js + " AddSelectOption(theSelectList, \"My Option\", \"123\", true);";
js = js + " function AddSelectOption(selectObj, text, value, isSelected) ";
js = js + "{";
js = js + " if (selectObj != null && selectObj.options != null)";
js = js + "{";
js = js + " selectObj.options[selectObj.options.length] = new Option(text, value, false, isSelected);";
js = js + "}}";
myIE.Document.Eval(js);
My setup
WatiN 2.0
IE8
Win7
Checked when the dropdown has 1 entry and 2 entries; both scenarios had "My Option" added without issue.

Getting the executed output of an aspx page after a short delay

I have an aspx page which has some javascript code like
<script>
setTimeout("document.write('" + place.address + "');",1);
</script>
As it is clear from the code it will going to write something on the page after a very short delay of 1 ms. I have created an another page to get the page executed by some query string and get its output. The problem is
I can not avoid the delay as simply writing document.write(place.address); will not print anything as it takes a little time to get values so if I set it in setTimeout for delayed output of 1 ms it always return me a value
If I request the output from another page using
System.Net.WebClient wc = new System.Net.WebClient();
System.IO.StreamReader sr = new System.IO.StreamReader(wc.OpenRead("http://localhost:4859/Default.aspx?lat=" + lat + "&lng=" + lng));
string strData = sr.ReadToEnd();
I get the source code of the document instead of the desired output.
I would like to either avoid that delay or else delayed the client request output so that I get a desired value not the source code.
The JS on default.aspx is
<script type="text/javascript">
var geocoder;
var address;
function initialize() {
geocoder = new GClientGeocoder();
var qs=new Querystring();
if(qs.get("lat") && qs.get("lng"))
{
geocoder.getLocations(new GLatLng(qs.get("lat"),qs.get("lng")),showAddress);
}
else
{
document.write("Invalid Access Or Not valid lat long is provided.");
}
}
function getAddress(overlay, latlng) {
if (latlng != null) {
address = latlng;
geocoder.getLocations(latlng, showAddress);
}
}
function showAddress(r) {
place = r.Placemark[0];
setTimeout("document.write('" + place.address + "');",1);
//document.write(place.address);
}
</script>
and the code on requestClient.aspx is as
System.Net.WebClient wc = new System.Net.WebClient();
System.IO.StreamReader sr = new System.IO.StreamReader(wc.OpenRead("http://localhost:4859/Default.aspx?lat=" + lat + "&lng=" + lng));
string strData = sr.ReadToEnd();
I'm not a JavaScript expert, but I believe using document.write after the page has finished loading is a bad thing. You should be creating an html element that your JavaScript can manipulate, once the calculation is complete.
Elaboration
In your page markup, create a placeholder for where you want the address to appear:
<p id="address">Placeholder For Address</p>
In your JavaScript function, update that placeholder:
function showAddress(r) {
place = r.Placemark[0];
setTimeout("document.getElementById('address').innerHTML = '" + place.address + "';",1);
}
string strData = sr.ReadToEnd();
I get the source code of the document instead of the desired output
(Could you give a sample of the output. I don't think I've seen a web scraper work that way so that would help me to be sure. But if not this is a good example web scraper)
Exactly what are you doing with the string "strData" If you are just writing it out, I recommend you putting it in a Server side control (like a literal). If at all possible, I'd recommend you do this server side using .net rather than waiting 1 ms in javascript (which isn't ideal considering the possibility that 1 ms may or may not be an ideal amount of time to wait on a particular user's machine hence: "client side"). In a case like this and I had to do it client side I would use the element.onload event to determine if a page has finished loading.

Categories