Is there a way to pass a parameter to a controller without putting it on the URL?
For example,
http://www.winepassionate.com/p/19/wine-chianti-docg-la-moto
has the value 19 on the URL. If you actually change that value to another, the page displays a different record even it the page name remains the same.
So I would like to NOT pass the ID on the URL but still be able to pass that to the Controller.
What's the recommended way to do so?
You can do a post and send it as a form parameter. I do not recommend this. Posts should be for requests that modify data. In this case you're most likely looking just to get that data. The fact that the id is in the URL is a good thing (see the Stack Overflow URLs for reference). If you really don't want the user to be able to modify it (I hope it's not because you think this makes it more secure, because it doesn't), you could do some simple encryption on it to make it more difficult to guess/produce a valid ID.
Using TempData, as some other suggest, is not a robust solution. It won't work for links on a page, just a GET after POST, and then only once since TempData is deleted after the next request.
Well, you have a couple of options:
Is this a form post? If so, then you can simply add a specific key value pair to your form when you submit it and then data will be passed along.
Is the URL unique to that resource? i.e. Does "Wine-chianti-docg-la-moto" exist as a unique representation of the number 19 in a database somewhere? If so, then you can simply do a lookup of that route component in your database to retrieve the value you need (or push that logic all the way down to the database).
Is that a value that is not expected to change a bunch? You can set that value in Session or in a cookie that would be persisted across pages and then pull it from the respective collection.
Are you redirecting to this page from another request on your server? If so, then you can use TempData to store this temporary value. However, I would recommend against this approach, as it is very transient and not good practice imo.
Lastly, you can obscure the value on the URL if you dont want it to be easily user editable. Encrypt it with some algorithm, and then decrypt it on the destination page. The user will be unlikely to be able to alter the ID by typing in a different value in the URL.
If the page is a GET, and you are following the PRG like you should be (Post-Redirect-Get) then you can use TempData["dataName"] = value; in your [HttpPost] controller and then consume it in your [HttpGet] method. It really depends on how the page is being called.
However, there is nothing wrong in letting the user change that number if it is not security related, and is common practice to show non-vital information in the url like that.
You should use TempData in this case. A good read on this can be found on this blog.
TempData allows you to store a value temporarily between requests and is, by default, erased after being accessed.
// TempData samplepublic ActionResult Featured(){ var featuredProduct = new Product { Name = "Assorted Cupcakes", Description = "Delectable vanilla and chocolate cupcakes", CreationDate = DateTime.Today, ExpirationDate = DateTime.Today.AddDays(7), ImageName = "cupcakes.jpg", Price = 5.99M, QtyOnHand = 12 };
Related
I'm working on rewriting an MVC application that currently utilizes cookies to hold data between multiple pages such as a date. I have tried to come up with an option that would hold the data in the controller by using something like this:
public DateTime HoldDate {get; set;}
The problem that I'm facing is that this is overwritten on each page load. I have also considered using Vue to store the variable and then sending the date to the controller on page load, but I'm not sure how to perform this.
Any help is appreciated and thank you in advance!
You can use TempDataDictionary to pass data from the controller to the view and back. It's a Dictionary, so you can access it with a key:
TempData["HoldDate"] = new DateTime(2020, 2, 13);
When you read data normally from TempData, it is automatically marked for deletion with the next HTTP request. To avoid that, since you want to pass this data around, use the .Peek() method, which lets you read the data but does not mark it for deletion.
var date = TempData.Peek("HoldDate");
If you need data to persist during the entire user session, you can use Session. For example user id or role id.
if(Session["HoldDate"] != null)
{
var holdDate= Session["HoldDate"] as DateTime;
}
If you need data only persist a single request - TempData. Good examples are validation messages, error messages, etc.
if (TempData.ContainsKey("HoldDate"))
{
var holdDate = TempData["HoldDate"] as DateTime;
}
TempData and Session, both required typecasting for getting data and check for null values to avoid run time exception.
Before I ask this question, I'm not even sure what I'm using is a query string (I'm so clueless on this, what I have is the result of some other confusing StackOverFlow research). It is a parameter I'm passing from my SSRS report viewer to my app via a hyperlink expression. It works and everything is grand except for I'd like to clear it from the url right afterwards.
http://10.155.54.101/Update?CurrencyId=67
And I am getting the parameter with this logic on page load.
if (Request.Params["CurrencyId"] != null)
int CurrencyId = int.parse(Request.Params["CurrencyId"]);
I am successfully capturing that information and populating asp.net controls with it but I want to clear it from the address bar now as it lingers after submitting the update (postback?).
Through another Stack Overflow Answer: Clear QueryString on PostBack , I've attempted to clear the querystring through the following code.
Request.Params.Clear();
But I get a collection is read-only error, which is addressed in the stack overflow question above. So I try to use System.Reflection to change the read only property of the collection with the following code.
PropertyInfo Isreadonly = typeof(System.Collections.Specialized.NameValueCollection).GetProperty("IsReadOnly", BindingFlags.Instance | BindingFlags.NonPublic);
Isreadonly.SetValue(Request.Params, false, null);
Request.Params.Clear();
I don't get the error but nothing is removed, so I might not be referencing the querystring properly because of however the heck Request.Params works.
Can someone nudge me in the right direction with this? I'm so sorry I'm clueless as heck on this.
You can't just change the URL in the address bar of a browser. You could redirect the browser to the URL without the query string, but seeing how you are using the value to populate controls on the page being render that would mean you would need to still need to have that value.
When you say "it lingers after submitting the update", do you mean the user chooses the currency and is redirected to the the page with this query string? If so could you change this action to a POST instead of a GET? Then you could put the currencyId in the body of the POST. If you can't switch it to a POST, then there are a few ideas I listed below.
If you are using session, you could store the currencyId in the user's session. But that would only make sense if you needed to use this value on other requests; as using session is a big decision and if you can keep your website stateless you should.
With that being said, there are two viable options to keep your site stateless. If you need this value on future requests, you can store it in a cookie. If you only need it on this request, you could have the page do post to the URL without the query string but with the value in the POST body.
I use asp.net 4, c# and Routing for my web site.
My Route result like
A) http://mysite.com/article/58/mytitle (result my article all is fine)
58 and mytitle represent in Id and Title Column in DataBase for my Articles table.
I notice that... if I request:
http://mysite.com/article/2000000000/mytitle (a not existing ID)
I receive an Error page.
If instead I try:
B) http://mysite.com/article/58/mytitttttttle (title misspelled)
I still get my page http://mysite.com/article/58/mytitle
I would need to have my website redirect to a 404 page if both the ID or the TITLE do not not represent any record in my DataSource.
PS: I notice that SO website has a similar behavior, apart that they are able to redirect to a 404 page if the ID for a questions does not match.
My questions:
is this a normal behavior?
how to redirect to 404 pages instead?
if is not possible to use 404 pages would make use canonical urls?
I asked because I'm concerning on this scenario, lets imagine a website link wrongly to my site like
http://mysite.com/article/58/mytitttttttle (title misspelled)
or
http://mysite.com/article/58/mytitttttttle2222 (title misspelled)
both will be index my Search Engine and resulting in duplicate content (and it is not good).
Please provide me a sample of code if possible. I appreciate your comment on this, thanks!
The reason this happens is because it uses the numerical id as the search key (in this case it looks for post 58 no matter what).
What you could do is either
get rid of numerical id, and stick with just text OR
retrieve the post, and verify the "postslug" is correct based on what you pulled out from database.
By using just text, you get a cleaner url. However you have to rely on your database indexing your strings in order to have high performance lookup on your postslug. And you have to worry about duplicate slugs.
By using the hybrid, you have less clean url (extra info), but you don't need to worry too much about integer lookup performance.
Which ever choice you pick, you verify this information in your controller, then either return View, or return HttpNotFound()
Hi I did this recently and used this blog which helped alot
http://weblogs.asp.net/paxer/archive/2010/05/31/asp-net-http-404-and-seo.aspx
http://searchengineland.com/url-rewriting-custom-error-pages-in-aspnet-20-12234
Rather than passing the ID and Title, I would recommend saving the Title as a unique value in the database so you can just have:
http://mysite.com/article/title
What happens if there are two titles? Well, then you can create a loop until you find a unique one incrementing an integer at the end like:
http://mysite.com/article/title-2
This gets around the issue of their being an ~infinite number of possible URLs which all point to the same page (which Google will hate you for)
Alternatively, if you wish to keep your URL with both the ID and Title in place, then on your web form run an if statement which returns how many records in the database match the variables.
Something like:
cmd.CommandText = "SELECT COUNT(*) FROM Table WHERE ID=#ID AND Title=#Title"
if ((int)cmd.executescalar == 0){
Response.Redirect("404.aspx");
}
I have stored a string value in a hidden field of a page.
How to access it from a different webpage?
You have two options.
a. Putting that string value in a Session.
string value="value";
Session["myValue"] = value;
b. Transmitting that value in the url.
string value="value";
Response.Redirect("./Mypage.aspx?value="+value);
On the page that contains the hidden value, you could post that form to the other page and get the value from this.Request.Form["hidden-field"].
Is that the sort of answer you are looking for? Maybe more details would help.
Good luck!
If you don't mind using jQuery, and as long as the pages are on the same domain, then you can do it with the .load() method. This method basically does a GET request to the page
Page with hidden field
<div id="hiddenValue">Value</div>
Page you're calling from
$('#newDiv').load('path/to/page.aspx #hiddenValue');
additional notes:
Due to browser security restrictions, most "Ajax" requests are subject to the same origin policy; the request can not successfully retrieve data from a different domain, subdomain, or protocol.
If they are on different domains then your only other options are:
Query Strings
Sessions
references:
http://api.jquery.com/load/
http://www.java2s.com/Code/ASP/Request/GetquerystringfromRequestC.htm
http://msdn.microsoft.com/en-us/library/ms178581.aspx
You can also use cookies to transfer the value across pages. May be you would want to read this piece of article to know more about the state management. Do read it. Will definitely gonna help you. You can decide what you want to use after reading this.
Hope it helps you. http://www.codeproject.com/KB/vista/ASPNet_State_Management.aspx
I have 2 webforms with 1 ListBox Control on each of them.
How do I access the Listbox that's located on webformA from webformB?
For example I wish to declare something like this string name = ListBoxWebformA.SelectedValue.ToString(); on WebFormB, so that I can work with that value in the code of WebFormB.
The ListBox on WebFormA lists several names.
When I select a name from the listbox and press the OK button I call Response.Redirect("~/WebFormB.aspx");
So from WebFormB I wish to access this "name" by putting the selected value into a string.
Based on your edit, the easiest (possibly best) way to go about doing this will not be to try to maintain a stateful instance of webformA during the request to webformB. Once the user is redirected, assume that webformA is gone.
Instead, when you're about to perform the Response.Redirect() to webformB, include in some way the value from webformA that you wish to pass along. The easiest way to do this will be on the query string. Something like:
Response.Redirect(string.Format("~/WebFormB.aspx?name={0}", HttpUtility.UrlEncode(ListBoxWebformA.SelectedValue.ToString())));
Then, in webformB you can access the value:
string name = Request.QueryString["name"];
Note that you'll want to do some error checking, etc. Make sure the value is actually selected before appending it to the redirect URL on webformA, make sure Request.QueryString["name"] contains a value before using it in webformB, etc.
But the idea in general is to pass that value along, by query string or POST value or Session value or some other more stateful means, when redirecting from one form to the other.
I guess you have to resort to either passing the value from A to B in the query string or storing the value in Session and reading afterwards.
So would be a
Response.Redirect(string.Format("~/WebFormB.aspx?YourVariable={0}",HttpUtility.UrlEncode(ListBoxWebformA.SelectedValue));
and you can read it in Form B like
Request.QueryString["YourVariable"]
If the values are not sensitive this approach above would be the best.
If they are... To store in Session:
Session["YourVariable"] = ListBoxWebformA.SelectedValue
And to read...
if (Session["YourVariable"] != null) {
var listAValue = Session["YourVariable"].ToString()
}