Asp.net MVC putting # in the url - model-view-controller

We are using Asp.net MVC, one of our requirement is to put '#' in the url something like
www.xyz.com/a-to-b/#date
i have registered the route below, it works fine for 'to' in the url but using # before the date i get a null data back. Is '#' some special character and required a different treatment.??
routes.MapRoute(
"routename",
"{origin}-to-{destination}/#{outDate}",
new
{
controller = "Home",
action = "ActionName",
});

The hash value (string starting from #) will never be sent to server. If you need access to the hash value you can use the following approach - How to get Url Hash (#) from server side .
Also it seems to me that you need to implement some kind of ajax navigation with history support. If I'm right then check this article - http://stephenwalther.com/blog/archive/2010/04/08/jquery-asp.net-and-browser-history.aspx

Related

Is there a DNN URL decode method as it is changing a URL Encode

We are using Server.URLEncode to change an SKU with a forward slash from BDF5555/45 to BD5555%2F45 in our Href on a button.
When a person clicks on the button the page navigates to another module which has Request.QueryString but DNN is changing the URL.
How can I get the variable decodeprodCode to include the &45 as BDF5555/45?
Perhaps DNN is rewriting the URL?
There is a NavigateURL class in DotNetNuke.Common.Globals that will generate a correct url based on a TabID and a lot of overloads.
DotNetNuke.Common.Globals.NavigateURL(TabId)
You can also use querystring parameters
DotNetNuke.Common.Globals.NavigateURL(TabId, ControlKey,"key=value"))
DNN by default will re-write querystring values into /key/value format in the URL assuming that it is properly encoded. For example if you have querystring values of sku=1 and productid = 2 the resultant URL will be
https://yoursite.com/Your-Page/sku/1/productid/2
This is done via the FriendlyUrlProvider, but it should not have any impact to your ability to process via Request.Querystring as this is a very, very common practice for passing values into DNN.
Your code to retrieve the value is correct.
I ended up using the following code instead of a Request.Querystring.
string RawurlFromRequest = Request.RawUrl;
var cleanSKU = RawurlFromRequest.Split(new[] {"sku/"}, StringSplitOptions.None)[1];
var CleanSKUNoOtherQueryStrings = cleanSKU.Split(new[] {"&"}, StringSplitOptions.None)[0];
The Request.RawURL brings back the URL with the special characters as it is without encoding. As Mitchel Sellers mentioned above, DNN uses the FriendlyURLProvider which rewrites the URL.
For example www.mysite.com/ProductFilter/SKU/BDF5555/45 and not
www.mysite.com/ProductFilter/SKU/BDF5555%2F45
The CleanSKU variable will look for SKU/ and split everything on the left as it is set to [1].
After everything has been split on the left, we look for other QueryStrings which we usually add with a & sign. We will split everything on the right by setting it to [0].
This will bring back BDF5555/45 in the backend with a forward slash which we can use to retrieve product information from our ERP system which URLdecode couldn't do.

Pass special character through query string in ASP.NET MVC 4

When I try to pass some special characters, though query string in the URL property of the Ajax post method, it seems to be some error happened. That means I won't get correct special characters when hitting controller action in ASP.NET MVC 4.
My code is
var temp=temp##$#%#%#979
url=(Controller/Action/id/name?departname=+temp);
request from a script function from a cshtml formajax
If you are making your ajax request from javascript, then use encodeURIComponent:-
var temp = encodeURIComponent('temp##$#%#%#979'); //temp%40%23%24%23%25%23%25%23979
use HttpUtility.UrlEncode for encoding the parameter
var temp = temp##$#%#%#979
HttpUtility.UrlEncode(temp)
url = (Controller/Action/id/name?departname=+temp);
and use Server.UrlDecode for decoding the parameter in controller
var Depart = Server.UrlDecode(Request.QueryString["DepartmentName"]);
I'm not familiar with ASP.net, however most languages require you to URL encode strings that are meant to be used as part of a URL.
For example:
https://msdn.microsoft.com/en-us/library/4fkewx0t%28v=vs.110%29.aspx
I hope this helps get you moving in the right direction.

Html.ActionLink where id is URL path causes 404

I have limited knowledge so beat me up as needed.
I have created a controller using the EF with ASPX(C#) views. I inherited this setup.
The PK in the target table/EF is an actual URL. So when you click the link ActionLink feeds the URL and I receive a 404.
Html.ActionLink("Edit", "Edit", new { id=item.ImagePath })
So id= /foldername/foldername2/image.jpg
This causes the browser to try and load the resource.
Can someone give me a clue how to process this "id" accordingly?
Have you changed your routing to accept this sort of id?
If not then you will need to go into your global.asax.cs file and edit the map routes.
This should help you with that:
Creating custom routes
The EDIT action in the controller... is waiting for a string ID or Integer one?
If the EDIT action accepts strings, then you could just scape the ID's "/"... that way the routing engine will no think the ID is a URL.

Make the route parameter actually appear in the address bar

I have a tiny application in MVC 3.
In this tiny application, I want my URLs very clear and consistent.
There's just one controller with one action with one parameter.
If no value is provided (that is, / is requested by the browser), then a form is displayed to collect that single value. If a value is provided, a page is rendered.
The only route is this one:
routes.MapRoute(
"Default",
"{account}",
new { controller = "Main", action = "Index", account = UrlParameter.Optional }
);
This all works fine, but the account parameter never appears in the address line as a part of the URL. I can manually type test.com/some_account and it will work, but other than that, the account goes as a post parameter and therefore does not appear. And if I use FormMethods.Get in my form, I get ?account=whatever appended to the URL, which is also not what I want and which goes against my understanding. My understanding was that the MVC framework would try to use parameters set in the route, and only if not found, it would append them after the ?.
I've tried various flavours of setting the routes -- one route with a default parameter, or one route with a required parameter, or two routes (one with a required parameter and one without parameters); I've tried mixing HttpGet/HttpPost in all possible ways; I've tried using single action method with optional parameter string account = null and using two action methods (one with parameter, one without), but I simply can't get the thing appear in the URL.
I have also consulted the Steven Sanderson's book on MVC 3, but on the screenshots there are no parameters either (a details page for Kayak is displayed, but the URL in the address bar is htpp://localhost:XXXX/).
The only thing that definitely works and does what I want is
return RedirectToAction("Index", new { account = "whatever" });
But in order to do it, I have to first check the raw incoming URL and do not redirect if it already contains an account in it, otherwise it is an infinite loop. This seems way too strange and unnecessary.
What is the correct way to make account always appear as a part of the URL?
My understanding was that the MVC framework would try to use
parameters set in the route, and only if not found, it would append
them after the ?
Your understanding is not correct. ASP.NET MVC doesn't append anything. It's the client browser sending the form submission as defined in the HTML specification:
The method attribute of the FORM element specifies the HTTP method used
to send the form to the processing agent. This attribute may take two
values:
get: With the HTTP "get" method, the form data set is appended to the URI specified by the action attribute (with a question-mark ("?")
as separator) and this new URI is sent to the processing agent.
post: With the HTTP "post" method, the form data set is included in the body of the form and sent to the processing agent.
ASP.NET MVC routes are used to parse an incoming client HTTP request and redispatch it to the corresponding controller actions. They are also used by HTML helpers such as Html.ActionLink or Html.BeginForm to generate correct routes. It's just that for your specific scenario where you need to submit a user entered value as part of the url path (not query string) the HTML specification has nothing to offer you.
So, if you want to fight against the HTML specification you will have to use other tools: javascript. So you could use GET method and subscribe to the submit handler of the form and inside it manipulate the url so the value that was appended after the ? satisfy your requirements.
Don't think of this as ASP.NET MVC and routes and stuff. Think of it as a simple HTML page (which is what the browser sees of course) and start tackling the problem from that side. How would you in a simple HTML page achieve this?

need help with mvc & routes

I'm very new to MVC and I'm trying to get a new site set up using it. For SEO reasons we need to make the url of a page something like "Recruiter/4359/John_Smith" or basically {controller}/{id}/{name}. I have that working when I create the url in the code behind like so...
//r is a recruiter object that is part of the results for the view
r.Summary = searchResult.Summary + "... <a href=\"/Recruiter/" + r.Id + "/" + r.FirstName + "_" + r.LastName + "\">Read More</a>"
But when I am using the collection of results from a search in my view and iterating through them I am trying to create another link to the same page doing something like <%=Html.ActionLink<RecruiterController>(x => x.Detail((int)r.Id), r.RecruiterName)%> but that doesn't work. When I use that code in the view it gives me a url in the form of /Recruiter/Detail/4359 I was told by a coworker that I should use the Html.ActionLink to create the link in both the view and the controller so that if the route changes in the future it will automatically work. Unfortunately he wasn't sure how to do that in this case. So, my problems are...
How can I make the Html.ActionLink work in the view to create a url like I need (like r.Summary above)?
How do I use the Html.ActionLink in a controller instead of hardcoding the link like I have above?
I came across this blog post which got me going in the right direction.
http://www.chadmoran.com/blog/2009/4/23/optimizing-url-generation-in-aspnet-mvc-part-2.html
It is a good idea to use the ActionLink method to write out links as your coworker says, that way they will always match your routes.
In your current case the reason it is writing out the method is because it is based on the default routing. You can fix this by adding another route above the default one in the Global.asax. You just need to stipulate the format you want like this:
routes.MapRoute(
"Recruiter",
"Recruiter/{id}/{name}",
new { controller = "Recruiter", action = "Details" }
);
MVC will work through your routes in the order they are registered so putting this before the default will make it use your route instead.
EDIT:
You might find this route debugging tool useful.

Resources