mvc - current URL? not request URL - asp.net

I am using Ajax.BeginForm to submit data etc, but when I look at Request.Url etc I get the URL of the Ajax request. Is there a way I can get URL of the actual page the user is on?
Basically, I need to obtain id (routevalue) from the URL without passing anything to the Ajax-actionlink.

Why not directly pass the information you need in the request:
<%: Ajax.ActionLink(
"Some link text",
"ActionName",
// Notice how the id value is extracted from the route
// and used to construct the link
new { id = RouteData.Values["id"] },
new AjaxOptions { OnSuccess = "success" }
) %>

You could try using the UrlReferrer property of the HttpRequest class. I'm not sure if it will work on every case of your application, but you could give it a try.

Related

Making id'less url in asp.net mvc razor

I am working with URL routing , and have some issues. I want my url to be like this:
www.domain.com/p/myproduct
But I also want to be able to retrieve the ID of the product, without accessing the database. I thought about having a URL like:
www.domain.com/p/myproduct/1
But if I could hide the ID it would be better.
So, how do I do it the simplest way?
Currently my Global.asax has the following route:
routes.MapLocalizedRoute("Product",
"p/{productId}/{SeName}",
new { controller = "Catalog", action = "Product", SeName = UrlParameter.Optional },
new { productId = #"\d+" },
new[] { "Nop.Web.Controllers" });
If all you have is the url then you will have to include the ID there if you want to read it.
The only way to hide it is if you have the ID coming to you from the post of a form say, assuming they have come from a previous page. Then you could store the selected Id and post to url as part of the request.

Wrong URI after Form Submit MVC 3 asp.NET

I'm a little confused on something here. I have a form, and the URL for that form is:
http://domain.com/Home/requestquote
When I click submit on a form and the method handling this form located in the form controller sends back a view, the URI looks like this:
http://domain.com/form/requestQuoteSubmit where requestQuoteSubmit is the method.
This occurs both when validation sends the page back for errors and when there is a successful form submit.
On success the view being sent back is Home/thanks and on error it should just send back Home/requestquote. Everything seems to work fine except for the fact that the URI is not what it is supposed to be. This causes everything else on the page to break because my links look like this:
#Url.RouteUrl(Model.CompanyPageDatabaseModel.companyCode, new { Controller = MVC.services.Name, Action = MVC.services.ActionNames.page })
So that companyCode value isn't being passed around properly and forming the links correctly. I'm not sure how or why the form method is sending back the correct page, but setting the URI to itself?
Here are my routes.
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
null,
"{action}",
new { controller = MVC.Home.Name, action = MVC.Home.ActionNames.Index },
new { RootAction = new RootActionConstraint() } // Route Constraint
);
routes.MapRoute(
null, // Route name
"{controller}/{action}", // URL with parameters
new { controller = MVC.Home.Name, action = MVC.Home.ActionNames.Index }, // Parameter defaults
new { controller = "Home|contact|franchise|form|resources|services|technology|community|careers|carriers|about" }
);
routes.MapRoute(
null,
"{companyCode}/{action}",
new { controller = MVC.Home.Name, action = MVC.Home.ActionNames.Index },
new { RootAction = new RootActionConstraint() } // Route Constraint
);
routes.MapRoute(
"jax",
"{companyCode}/{controller}/{action}",
new { controller = MVC.Home.Name, action = MVC.Home.ActionNames.Index }
);
The last route value is an example of a franchisee route.
Also here is the form code in the view:
#using (Html.BeginForm("requestquote", "form", FormMethod.Post))
{ }
Any ideas?
Thanks.
Edit: Added in my routes.
There is a concept referred to as PRG, which stands for Post-Redirect-Get.
The basic idea is that you Post the form to your application. After processing the input, you then Redirect to a Get request at the correct URL, instead of serving the user a content response directly from the submission.
This is good for many reasons, but the underlying one is separation of concerns. (When you don't separate concerns weird stuff like all the links might breaking on your page tends to happen...)
So, the solution for you is to process the submission, and if invalid, store your Validation content in TempData and return a RedirectToRouteResult(controller:"Home",action:"RequestQuote")
Update: I found the original article I read to learn this concept. It's in terms of the original ASP.NET MVC release, but it should be mostly the same. Check out http://www.eworldui.net/blog/post/2008/05/ASPNET-MVC---Using-Post2c-Redirect2c-Get-Pattern.aspx

ASP.NET 4.0 URL routing with two or multiple querystring parameters

How can I pass two querysting parameters in URL routing using ASP.NET 4.0?
I have gone through many articles, but everywhere it shows only one parameter.
I'd like the display URL to be:
http://www.mywebsite.com/reports/1-this-is-my-first-report
The first parameter is ID: 1
The second is Name: This is my first report
I am trying following route, but it is not working
routes.MapPageRoute(
"MarketReports", // Route name
"Reports/{*i}-{*n}", // Route URL
"~/pageControl2.aspx" // Web page to handle route
);
How can I make this work as described?
Try formatting the URL this way:
http://www.mywebsite.com/reports/1/this-is-my-first-report
routes.MapPageRoute(
"MarketReports", // Route name
"Reports/{*i}/{*n}", // Route URL
"~/pageControl2.aspx" // Web page to handle route
);
Try this
Response.RedirectToRoute("UrlRouting for Querystring",
new { name = txtsearchurlrouting.Text, text = txtsearchid.Text });
In Global.asax
routes.MapPageRoute("UrlRouting for Querystring",
"Querystring/Selected/{name}/{text}/", "~/Address.aspx");
like this we can pass multiple querystring parameters

How to hide controller name in Url?

How to hide controller name in Url?
I use the ASP.NET MVC.
The original url is: http://www.sample.com/Users.mvc/UserDetail/9615
The "Users" is controller name, the "UserDetail" is action name, and the "9615" is UserId.
How can I hide the controller name and action name in the url.
Just like this: http://www.sample.com/9615
I have writed the following code in the Global.ascx.cs to hide the action name:
routes.MapRoute(
"UserDetail", // Route name
"Users.mvc/{UserId}", // URL with parameters
new { controller = "Users", action = "UserDetail", UserId = "" } // Parameter defaults
);
Using the above code I hid the action name and got this url: http://www.sample.com/Users.mvc/9615
But how can I hide the controller name and get this url: http://www.sample.com/9615
Thanks.
The idea is the same. You do just the thing you did to the action. However, your problem arises from the fact that IIS is probably not mapping www.xyz.com/1234 to ASP.NET runtime. To do so in IIS7, enable integrated mode and in IIS6, add a wildcard mapping in handler map that maps everything to ASP.NET.
To add a wildcard map, see http://haacked.com/archive/2008/11/26/asp.net-mvc-on-iis-6-walkthrough.aspx (Search for "IIS6 Extension-less URLs" in that page)
After that, simply add a route:
routes.MapRoute("UserDetails", "{UserID}/{*name}",
new { controller = "Users", action = "UserDetail" , UserID=""});
This should do the trick.
MVC recognizes the difference between "{UserID}" and "{id}" so if you are going to have a route with only "{UserID}" in the Url you need to place it first in the list other wise it never gets hit. And make sure the default includes "id" since it will continually loop over "UserDetails" unless the default references id as apposed to UserID. I found this format works for me:
routes.MapRoute("UserDetails",
"{UserID}",
new { controller = "Users", action = "UserDetail", id = "" }
);
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Account", action = "LogOn", id = "" } // Parameter defaults
);

Creating a URL in the controller .NET MVC

I need to be able to construct a link in the Action on the controller to send an email. What is best practice to do this? I don't want to construct it myself in case my routes change.
Should I have a view for each email and render that and send it? That might be a good way of doing it.
If you just want to get the path to a certain action, use UrlHelper:
UrlHelper u = new UrlHelper(this.ControllerContext.RequestContext);
string url = u.Action("About", "Home", null);
if you want to create a hyperlink:
string link = HtmlHelper.GenerateLink(this.ControllerContext.RequestContext, System.Web.Routing.RouteTable.Routes, "My link", "Root", "About", "Home", null, null);
Intellisense will give you the meaning of each of the parameters.
Update from comments: controller already has a UrlHelper:
string url = this.Url.Action("About", "Home", null);
If you need the full url (for instance to send by email) consider using one of the following built-in methods:
With this you create the route to use to build the url:
Url.RouteUrl("OpinionByCompany", new RouteValueDictionary(new{cid=newop.CompanyID,oid=newop.ID}), HttpContext.Request.Url.Scheme, HttpContext.Request.Url.Authority)
Here the url is built after the route engine determine the correct one:
Url.Action("Detail","Opinion",new RouteValueDictionary(new{cid=newop.CompanyID,oid=newop.ID}),HttpContext.Request.Url.Scheme, HttpContext.Request.Url.Authority)
In both methods, the last 2 parameters specifies the protocol and hostname.
Regards.
I had the same issue, and it appears Gidon's answer has one tiny flaw: it generates a relative URL, which cannot be sent by mail.
My solution looks like this:
string link = HttpContext.Request.Url.Scheme + "://" + HttpContext.Request.Url.Authority + Url.Action("ResetPassword", "Account", new { key = randomString });
This way, a full URL is generated, and it works even if the application is several levels deep on the hosting server, and uses a port other than 80.
EDIT: I found this useful as well.
Another way to create an absolute URL to an action:
var relativeUrl = Url.Action("MyAction"); //..or one of the other .Action() overloads
var currentUrl = Request.Url;
var absoluteUrl = new System.Uri(currentUrl, relativeUrl);
I know this is an old question, but just in case you are trying to do the same thing in ASP.NET Core, here is how you can create the UrlHelper inside an action:
var urlHelper = new UrlHelper(this.ControllerContext);
Or, you could just use the Controller.Url property if you inherit from Controller.

Resources