Been working on a classic asp page. I've been using Request.Form("x") and saw that I can also use Request("x") to accomplish the same result.
What is the difference between the two? If they're the same I'll just use the later as it saves me some typing :)
The HttpRequest.Item property will search for the specified key in the QueryString, Form, Cookies, or ServerVariables collections.
The HttpRequest.Form property will only search among form variables.
Related resources:
HttpRequest Class
Request.Form(x) will check only the posted data whereas Request(x) checks the query string as well.
Related
What is the difference between these two in VBScript:
Request("startDate")
Request.QueryString["startDate"]
And where is Request("startDate") documented? I don't see this usage here:
http://www.w3schools.com/asp/asp_ref_request.asp
The official documentation for the Request object in ASP classic is here: http://msdn.microsoft.com/en-us/library/ms524948%28VS.90%29.aspx
Quoting the relevant part for this question:
All variables can be accessed directly by calling Request(variable)
without the collection name. In this case, the Web server searches the
collections in the following order:
QueryString
Form
Cookies
ClientCertificate
ServerVariables
If a variable with the same name exists in more than one collection,
the Request object returns the first instance that the object
encounters.
EDIT: AnthonyWJones made a great comment on the question: Avoid using the Request("name") syntax. In fact, this is mentioned in the documentation link above:
It is strongly recommended that when referring to members of a
collection the full name be used. For example, rather than
Request.("AUTH_USER") use Request.ServerVariables("AUTH_USER"). This
allows the server to locate the item more quickly.
See Request() vs Request.QueryString()
From what I understand when you use Request on it's own it will return the first matched item in the request collection. well explained in the attached solution.
Sorry to dredge up this question, but given the warnings against using Request("param"), I had to add my two cents. In this particular case there's a good reason to use Request("param") instead of Request.QueryString("param"): It allows you to write code that will accept parameters as part of a query string or when submitted through a form. I regularly run into situations where that is not only handy, but desirable.
I need to get some Json to the client side from the server and it's somewhat troublesome as almost all tutorials assume an Ajax call to a separate action to get the Json.
This led me to think that there must be some reason why it is done this way. In Asp.Net MVC we can pass a Model along with the view to get the information but we can't seem to easily pass a Json object. Instead you are supposed to make a separate call to get this information.
What if the Json info is known when the page is generated, why not generate it at the same time?
I'm sorry if I wasn't clear enough. While it's nice to hear of ways to get Json to the client, the question is actually whether there is a specific reason the Ajax call method is much more popular, like security or anything like that.
Can you put something like this into your view? (rough pseudo code, assuming using a Razor view)
< script >
var myJSON = { Field: #model.Field, Field2: #model.Field2 };
< /script >
Because you do not need both at the same time... on the first call will be to get html (the view of the data - represented by a view model), and any ajax calls will be to get the possibly updated data (json serialized view model).
No reason why you can't. You could use the javacript serializer to create a JSON string that drop on the page. You could also create an action that return the json string that you called from a script tag.
What you want if you're using KnockOut, would be the Mapping plugin that turns an ordinary JS object, like that generated above, into an observable ready for KnockOut to use. See here from info. http://knockoutjs.com/documentation/plugins-mapping.html
You can use content-negotiation by setting accept header. This is considered a best practice (and according to some RESTful).
This needs to be supported and implemented at server as well. ASP NET MVC does not make it easy to support content-negotiation and you have to implement it yourself by if-else or using ActionFilter and implementing action selector.
Is there a standard way to create unique web page address in ASP.NET? I'm sending surveys to customers and will be including a link to the web page. For example:
http://www.mysurveypages.foo/survey/UniqueID
I would then customize the survey based on who I sent it to. I know it can be done by passing in a unique parameter to a page but I curious about doing it this way.
You can use Routing to map your url structure onto a particular page and parameter collection. Essentially, it allows you to convert parts of the url into url parameters for your page. This works in standard WebForms and is the basis upon which MVC chooses the appropriate controller/action signature to invoke.
Yup like dcp said GUID is a reasonable solution http://mywebsite.com/survey.aspx?ID=GUID
Suppose you are going to sent the survey to a list of users.
List<User> users = GetSurveyUsers();
foreach(User u in users)
{
Guid guid = Guid.NewGuid();
//Then store the user-guid pair into DB or XML...
}
The simplest solution would seem to be making UniqueID an incrementing field that can be used to get the appropriate user information out of the database. You could use numbers, or a Guid, or some alpha-numeric value, it really doesn't matter.
If you go with ASP.Net MVC then it is quite easy to map the Url (like the one you specified) to a controller action which gets the ID passed in as a parameter. Otherwise you will probably want to look into some sort of Url rewriting to make sure the Url can be nice and pretty.
A GUID approach is safest, if you're able to store it somewhere. If not you could use some existing unique data (e.g. customer id or email address) either directly (but be careful about leaking sensitive data) or hashed (but need to consider collisions).
Is there a way I can remove null or empty keys from a query string in asp.net MVC? For example I have a page where I filter data on a results table, if I search for John the query string would be redisplayed as:
candidates?FirstName=John&LastName=&Credit=false&Previous=false&Education=&Progress=
and not
candidates?FirstName=John
I looked at URL routing but I wasn't sure if it was something that should be used for cosmetic things like this or if it is possible to achieve what I'm asking using it.
How are you generating that URL? With Routing, if those are meant to be in the query string, it should work fine. We only generate query string parameters for RouteValues that you specify.
One thing I've done in the past is to write my own helper method for specific links where I might pass in an object for route values, but want to clear out the values that I don't need before passing it to the underlying routing API. That worked well for me.
Whatever URL generator, or control you are using would need special logic to strip these unwanted tags from the list. It's not obvious to a generic URL generator or control that Credit=false is useless -- couldn't it be Credit=true is the default? Similarly an empty string can mean something. (Also, Lastname= is different from Lastname.
I sometimes need to work on my route values in partials that are used by variuos views.
Then I usualy access the routeDictionary and change it. The benefit you get is, that there is a good chance that the code will survive changes in the routing and that you can use routeValues in multiple generated URL.
Most people would argue that the best place for this code is not the view. But hopefully you get the idea.
The view code:
RouteValueDictionary routeValues = ViewContext.RouteData.Values;
routeValues.Remove(...);
routeValues.Add(...);
routeValues["Key"] = ...;
<%
using (Html.BeginForm(
Url.RequestContext.RouteData.GetRequiredString("Action"),
Url.RequestContext.RouteData.GetRequiredString("Controller"),
routeValues,
FormMethod.Get))
{ %>
Maybe use this Querystring Builder - iterate querystrings in the Request.QueryString dictionary and build a new one using the builder (or just string-concat them)?
We heard a lot about the vulnerabilities of using QueryStrings and the possible attacks.
Aside from that, yesterday, an error irritated me so much that i just decide to stop using QueryStrings, i was passing something like:
Dim url As String = "pageName.aspx?type=3&st=34&am=87&m=9"
I tried to
Response.Write(url)
in the redirecting page, it printed the "type" as 3, then i tried it in the target page, it printed 3,0....i know this can be easily dealt with, but why? i mean why should i pass 3 and have to check for 3.0 in the next page's load to take my action accordingly???
So what should we use? what is the safest way to pass variables, parameters...etc to the next page?
You could use Cross-Page Postbacks.
Check also this article:
How to: Pass Values Between ASP.NET Web Pages
There are many options you can use, most of them requires you to build a strategy to pass variables between pages.
In most projects I use this strategy, I create a formVariables class to hold currently active items. it has properties which you will need to pass by querystring. and I store this class at session. and in my base page I read it from session. so in every page I get values over this object. the only negative thing about this method is to clean up items when you finished your work on it..
hope this helps.
I would sugest you avoid using Session to pass variables between pages as this breaks the stateless model of the web.
if you have just stored some values in session that relate to a certain page then the user uses their browsers back button to go back to the same page whcih should have a different state then you are not going to know about it.
It leads to the possibility of reading session values that are not relevant to the page the user is currently viewing - Which is potentially very confusing for the end user.
You will also run into issues with session expiration if you rely on it too much.
I personally try to avoid using session where possible in preference of hidden form values + query strings that can be read on postback + navigation.
The best / most secure way to pass info between pages is to use the session.
// On page 1:
this.Session["type"] = 3;
// On Page 2:
int type = (int)this.Session["type"];
You can store any kind of object in the session and it is stored on the server side, so the user can't manipulate it like a query string, viewstate, or hidden field
You said:
it printed 3,0....i know this can be easily dealt with, but why? i mean why should i pass 3 and have to check for 3.0
There's a difference between "3,0" (three comma oh) and "3.0" (three point oh). You also said that you were "passing something like".
In a query string, if you pass multiple values in the same key, they will be seperated with commas.
As all values are passed as strings there's no way that an int "3" is going to magically become decimal "3.0" unless you parse it as such when you request it.
I'd go back and double check what you are passing into your URL, if it ends up as something like:
pageName.aspx?type=3&st=34&am=87&m=9&type=0
Then when you read back
Request.QueryString["type"]
You'll get "3,0" back as the comma seperated list of values in that key.
First, in asp .net you can use several strategys to pass values between pages. You have viewstate too, however the viewstate store the value and the use is in different scenarios , you can use it too. Sessions instead, and of course by post in a form.
If your problem is the security, I recommended you to create 2 users for accesing the data. One user with read only access, this for accessing the pages ( Sql Inyection prevent ) and validate the data throw the querystring. And One with write access for your private zone.
Sorry, for my unreadeable English.
I like to use query string as I like users to be able to bookmark things like common searches and the like. E.g. if a page can work stand-alone then I like to it to be able to work stand-alone.
Using session/cross-page postbacks is cool if you needed to come from another page for the page you're on to make sense, but otherwise I generally find querystrings to be the better solution.
Just remember that query strings are unvalidated input and treat them with the caution you would treat any unvalidated input.
If you do proper security checks on each page load then the querystring is fine and most flexible IMHO.
They provide the most flexibility as the entry poitn to a page is not dependant on the sender as in some other options. You can call a page from any point within your own app or externally if needed via querystrings. They can also be bookmarked and manually modified for testing or direct manipulation.
Again the key is adding proper security and validation to the querystring, and not processing it blindly. Keep in mind that the seucirty goes beyond having edit or read access, depending on the data and user, they may not have access to the data with thos paranters at all, in cases where data is owned and private to specific users.
We have tried various methods, in an attempt to hide the querystring but in the end have gone back to it, as it is easier to do, debug, and manage.