I have an action link:
@Html.ActionLink("Shopping cart", "Index", "Cart", new { returnUrl = Request.Url.PathAndQuery }, null)
and code that adds items to cart:
<script type="text/javascript">
$(document).ready(function () {
$("#addToCart_@(Model.ProductID)").click(function () {
var quantity = $("#Quantity_@(Model.ProductID)").val();
var productId = "@Model.ProductID";
var dataToBeSent = { 'quantity': quantity, 'productId': productId};
$.ajax({
type: "POST",
url: '/Cart/AddToCart/',
data: dataToBeSent,
success: function (result) {
$('#cartholder').html(result);
}
});
});
});
</script>
When I'm trying to follow action link after adding item to cart, Request.Url.PathAndQuery
has value /Cart/AddToCart/
.
How can I get current url?
System.Web.HttpContext.Current.Request.Url
Looks to me like you are setting your URL to /Cart/AddToCart/
. It's right there in your AJAX request: url: '/Cart/AddToCart/'
. That's it -- that's your URL (not counting the scheme and host).
You're specifying type: "POST"
, so your payload (your data: dataToBeSent
) isn't sent as part of the URL. The data only gets sent in the URL when you use GET. When you use POST, it's in the request body, not the URL.
(And don't just change it to a GET. It would seem to work for now, but would give you headaches later. GET requests can be cached by proxy servers -- not appropriate for requests that modify state, like adding things to a shopping cart.)
So in answer to the question you asked, Request.Url.PathAndQuery
is how you get the URL. It's just that the URL is not what you want. You want to get your POST data, however that's normally done in ASP.NET MVC.
You need to use:
Request.RawUrl
This will get the URL you see in the browser. When using Url writing as with MVC the Request.Url will be the rewritten path.