Adding a "previous" link - asp.net-mvc

What the appropriate way to do this?
ViewData["PreviousPage"]=Request.UrlReferrer.PathAndQuery;
this doesnt work if directly accessing.
EDIT: I did a null check on Request.UrlReferrer, seems to be fine (?)

If directly, it's impossible this way. URL referer is set only when clicking a link.
If you're interested only in "Previous Page" link working inside your website, then you can store current URL in session, and retrieve it during next request, then replace with a new current url. Ugly, but working.

Is there some reason this needs to be server-side instead of client-side? If you can deal with client side, Javascript is the answer:
<input type=button value="Back" onClick="history.go(-1)">
This uses the browser's built-in back functionality -- it essentially mimics clicking the "Back" button.

Put this somewhere in your Base Controller or Custom Filter:
TempData["PreviousPage"] = TempData["CurrentPage"];
TempData["CurrentPage"] = Request.Url;

Related

Return to previous page in ASP.Net Core MVC

From my client detail page I have a button to edit the client record which redirects to an edit page. I have a "return to client detail" link on the edit page which I want to redirect the user back to the previous client detail page.
<a asp-controller="Client" asp-action="Detail" asp-route-id="#Model.ClientID">Return to client detail</a>
Currently this works as expected but takes extra time as it reloads the detail page from scratch (ie running all the various db queries again). Since the user is really just cancelling the edit without any changes to the state of the client I am wanting to return the user to the previous detail page without having to go through the controller action again.
Essentially I am wanting to simulate the browser back button (to improve responsiveness) but i'm not sure how to implement this or whether it's good practice to do so. Some guidance would be appreciated.
Thanks
For IActionResult you can use this code:
public IActionResult Test()
{
return Redirect(Request.Headers["Referer"].ToString());
}
U know what? I hate JS so i will write answer with backend side. The HTTP referer is an HTTP header field that identifies the address of the webpage that linked to the resource being requested. So simply read that and pass to view (always remember about XSS and validation, user can easly spoof HTTP request)
In action controller
if(Request.Headers["Referer"] != null)
{
ViewData["Reffer"] = Request.Headers["Referer"].ToString();
}
In view (razor)
#if(!string.IsNullOrWhiteSpace(ViewData["Reffer"]))
{
Return to client detail
}
You can use
<a href='javascript:history.go(-1)'>Return to client detail</a>
or onclick
Return to client detail
It should be like this
<input type="button" onclick= "history.go(-1)" value="Return to client detail" />
One note of caution using Request.Headers["Referer"] - if someone refreshes the destination page for some reason, Request.Headers["Referer"] will be empty.
Using history.go(-1) gives the expected behavior despite page refresh.
I think that you need to get rid of the idea of passing through the controller. If you need to browse quickliest with asp net core code about href you can try this.
<a asp-area="" onclick="history.go(-1);">Return to client detail</a>
I would never rely on my button, thinking a user will prefer it to browser back button.
I would say the correct way to solve this problem is to store the page state somewhere, for example, save ViewModel in TempData or Session. Then, if exists, load from it, instead of running db queries. It's quick and reliable.
This Request.Headers["Referer"] will not work if the user refresh the page or the page is been loaded twice, which mean, clicking back will not take you out of the current page.

How to properly encode links to external URL in MVC Razor

This view suppose to show a list of hyperlinks, each pointing to an external URL. The goal is for the user to click one of these links and have their browser open a new tab with the selected URL.
Currently I have the following markup:
#Html.ActionLink("SomeSite", "http://subdomain.mydomain.com/SomeSite")
This markup produces:
http://localhost:58980/AccessInstance/http%3a/subdomain.mydomain.com/SomeSite
instead of :
http://subdomain.mydomain.com/SomeSite
What can I change in my markup to make this work as I expect?
You don't need to use #Html.ActionLink for that. Just use a plain A tag:
SomeSite
Html.ActionLink is specifically for generating links to actions defined in MVC controllers, in the same app. Since you're linking to an absolute URL, you don't need any of the functionality that Html.ActionLink provides.
Two ways :
1. update the database column with full link:
eg SQL:
update ProductTable set ProductLink='http://www.example.com/Product/Mobiles' where ID=123
In asp mvc view
View
2. Hardcode the http part and list from model
View
Hope helps someone.
While a ViewBag is overused and not the best choice most of the time this is something that I had done when inheriting someone else's mvc app to do a quick fix for a URL that I needed to redirect to with a specific dynamically changing querystring parameter
<a target="_parent" href="http://localhost:56332/services/#ViewBag.factory">View Service</a>
Using .NET Core 6
This seems to be the most correct answer:
Link
This will generate the following result:
As you can see at the bottom left corner of the window before clicking the link, the URL address was rendered as it is (NOTE: The cursor was recorded out of place for some reason, that's a ShareX problem, ignore it).
Than link will be directly saved as a nvarchar(750) type (probably any character like type will do the work). No changes to the original link were made before saving it or on reading:
You need to take into account your RouteConfiguration.
routes.MapRoute(
name: "Default",
url: "{controller}/{action}"
because you are specifying the action link as the entire link that you want to redirect.
I would recommend that you use the #rossipedia answer because you can make tricky things like putting a span inside the link
Here to display link that are clickable in index page
<td>
#Html.ActionLink(item.FileName, "../Uploads/Catalogue/"+item.FileName)
</td>

how to get history.back value in javascript

How can i get the URL of the previous page in JavaScript?
I mean the value of this function:
history.back()
or this one :
history.go(-1)
For privacy reasons, you will never be able to do that.
In JavaScript, you use the document.referrer property, which will give you the URL of the page where the user came from.

GWT History Problem

when i am adding a new history item like this
History.newItem("Register");
the url correcly changes to
http://127.0.0.1:8888/BiddingSystem.html?gwt.codesvr=127.0.0.1:9997#Register
and loads the register form
but then the url automatically rechanges to
http://127.0.0.1:8888/BiddingSystem.html?gwt.codesvr=127.0.0.1:9997#
why??
because I want to remain as
http://127.0.0.1:8888/BiddingSystem.html?gwt.codesvr=127.0.0.1:9997#Register
so that user can reload
The problem is that I was using an hyperlink for acting like a click handler. with a hyperlink, event if u place an empty string, it gonna change the url.
e.g. if the current URL is something like http:...//#This and a hyperlink has an empty target history token then, the url is to change to http:...//#.
The solution i used that worked for me is that because i does not want to use a button, i make use of label and adding some css to it to make it look like a hyperlink
for e.g.
Label Register= new Label("register");
Label.setStyleName("FalseHyperlink");
then in the css
.FalseHyperlink
{
color:blue;
}
.FalseHyperlink:hover
{
text-decortion:underline;
}
Here this solution worked for me because i was not interested in other hyperlink services such as visited or others
Check if any empty string added to History after page rendered or correct history token added to history? URL is changed when a string added to History.

Is there a way to change the browser's address bar without refreshing the page?

I'm developing a web app. In it I have a section called categories that every time a user clicks one of the categories an update panel loads the appropriate content.
After the user clicked the category I want to change the browser's address bar url from
www.mysite.com/products
to something like
www.mysite.com/products/{selectedCat}
without refreshing the page.
Is there some kind of JavaScript API I can use to achieve this?
With HTML5 you can modify the url without reloading:
If you want to make a new post in the browser's history (i.e. back button will work)
window.history.pushState('Object', 'Title', '/new-url');
If you just want to change the url without being able to go back
window.history.replaceState('Object', 'Title', '/another-new-url');
The object can be used for ajax navigation:
window.history.pushState({ id: 35 }, 'Viewing item #35', '/item/35');
window.onpopstate = function (e) {
var id = e.state.id;
load_item(id);
};
Read more here: http://www.w3.org/TR/html5-author/history.html
A fallback sollution: https://github.com/browserstate/history.js
To add to what the guys have already said edit the window.location.hash property to match the URL you want in your onclick function.
window.location.hash = 'category-name'; // address bar would become http://example.com/#category-name
I believe directly manipulating the address bar to a completely different url without moving to that url isn't allowed for security reasons, if you are happy with it being
www.mysite.com/products/#{selectedCat}
i.e. an anchor style link within the same page then look into the various history/"back button" scripts that are now present in most javascript libraries.
The mention of update panel leads me to guess you are using asp.net, in that case the asp.net ajax history control is a good place to start
I don't think this is possible (at least changing to a totally different address), as it would be an unintuitive misuse of the address bar, and could promote phishing attacks.
This cannot be done the way you're saying it. The method suggested by somej.net is the closest you can get. It's actually very common practice in the AJAX age. Even Gmail uses this.
"window.location.hash"
as suggested by sanchothefat should be the one and only way of doing it. Because all the places that I have seen this feature, it's all the time after the # in URL.

Resources