Razor manipulate url - asp.net

I am using asp.net mvc to build a page where i have to show alot of users in a table. I would like to make a paged view with an url like:
mypage.com/Customer/{pageno}/{sorttype}/{somethingelse}
The urls would be located different places on a page. E.g. the "next page" button would have the same url, with just {pageno} increased, and the table headers would have {sorttype} different.
Is there a nice way to do this in razor, or will i just have to get the raw url, and parse it myself?
Thanks.

You should leave URL generation to ASP.NET MVC routing. In the global.asax you should configure route for your Customer page correctly so it can take pageno, sorttype and somethingelse parameters.
Then in Razor you should simply use Url.Action (or Html.ActionLink) method, so the URL would be generated for you. You can use following overload in your case:
http://msdn.microsoft.com/en-us/library/dd470197(v=vs.118).aspx
If you find it too complex to write stuff like #Url.Action("Index", "Customer", new { pageno = 1, sorttype = "type", somethingelse = "test"), then you can add another extension method like Url.MyAction which will take 3 parameters (int pageno, string sorttype, string somethingelse) and call Url.Action internally. However I wouldn't suggest doing that because the readability of your code will surprisingly decrease. Everybody know Url.Action method, while your new Url.MyAction would be something new to other developers reading your code.
Again, the key is correct routing, so Url.Action() will be rendered to "/Customer/1/type/test". You can find more information on the link below: http://www.asp.net/mvc/tutorials/older-versions/controllers-and-routing/asp-net-mvc-routing-overview-cs

Related

Is there an equivalent to GetRouteUrl() at application/class level (.Net 4.8)?

Within classic webforms ASPX pages, I create URL routes using the following:
var url = this.GetRouteUrl("MyRouteName", new {UserId = 123}); // Generates /UserId/123
MyRouteName is defined within the Routes.RegisterRoutes() method used at startup.
However, I need to generate a URL within a helper method that lives at application-level. There is obviously no page context there, so I get an error.
The MSDN documentation states:
This method is provided for coding convenience. It is equivalent to
calling the RouteCollection.GetVirtualPath(RequestContext,
RouteValueDictionary) method. This method converts the object that is
passed in routeParameters to a RouteValueDictionary object by using
the RouteValueDictionary.RouteValueDictionary(Object) constructor.
I read these, but cannot figure out whether what I need to achieve is possible. An online search revealed some answers, but these are many years old an not easy to implement.
The following works to generate the equivalent of GetRouteUrl at application/class level:
var url = RouteTable.Routes.GetVirtualPath(null,
"MyRouteName",
new RouteValueDictionary(new { UserId = 123 })).VirtualPath;
Remember that only returns a local Url (e.g. /UserId/123) so if you need to domain name you'll have to prepend that as well:
var url = HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority) + RouteTable.Routes.GetVirtualPath(null,
"MyRouteName",
new RouteValueDictionary(new { UserId = 123 })).VirtualPath;
I have in my Global.asax file in the Application_Start
RouteTable.Routes.MapPageRoute("Level1", "{lvl1}", "~/Routing.aspx");//Any name will do for the aspx page.
RouteTable.Routes.MapPageRoute("Level2", "{lvl1}/{*lvl2}", "~/Routing.aspx");
Then my Routing.aspx.cs page handles the logic for what will happen with the request.
Mainly I Server.Transfer to an aspx page which will display the requested page.
Routing.aspx page picks up any "non-existing" page.
Hope this helps or at least gives you some more ideas.

Trouble entering POST parameters into url for ".do" page

I'm doing some heavy web scraping using Python. In some cases, post data is sent not through a form submit but through some Javascript, which I cannot interact with via this approach. In order to circumvent this, I've been appending names and values for the post requests to the url and then visiting that url.
This method was working fine until I came across a site that used this kind of structure: [sitename].com/?[pagename].do/. I admit total ignorance about this .do extension, though some light searching tells me that it has to do with Struts and a Java-based backend. In this case it seems to be a way of dynamically generating a table; I'm trying to filter the results of that table. What I want to enter is something like [sitename].com/?[pagename].do?[name]=[value]&[name]=[value], but this doesn't work, nor does it even seem like it should work. I attempted it using several variations in syntax. It seems like something I don't quite understand is going on here.
I wish I could direct you to the actual site, but unfortunately I cannot due to the sensitive nature of the project. Let me know, though, if there's any additional information that would be helpful in providing an answer. Thanks in advance.
Edit: This is not really a "my code isn't working" question, as it's the underlying functionality that I would like to emulate in my code which is troubling me, but I'll do my best to get grittier. I'm contractually bound not to share the names of the sites that we're studying, but I will try to model the problem. I am hoping that someone with some familiarity of the back-end activity sending this .do page to the browser will be able to shed light.
import urllib
import urllib2
#
## case 1: a site that i have success in scraping
url = 'http://[sitename]/[pagename]'
values = {'s' : '40', 'pg' : '1'}
data = urllib.urlencode(values)
req = urllib2.Request(url, data)
response = urllib2.urlopen(req)
the_page = response.read()
print the_page #i get the filtered data that i am looking for
#
## case 2: the site that poses a problem for the encoding of post parameters
url = 'http://[sitename]/?[pagename].do/' # this site uses a .do file to generate
# the content i want to filter. note that the page name is preceded by ?.
values = {'s' : '40', 'pg' : '1'}
data = urllib.urlencode(values)
req = urllib2.Request(url, data)
response = urllib2.urlopen(req)
the_page = response.read()
print the_page # i am taken back to the root of the site,
# the same result i would get if i entered nonsense
# post parameters that did not correspond with actual control names.
here, also, is an example of some javascript on the page that accomplishes what i'd like to do with my scraper:
function page_next (id) {
$("#loading").fadeIn("normal");
$.post("/?dumps.do/", {s: id, pg: 2},
function( data ) {
var content = $( data ).find( '#dumps' );
}
)
}
I don't know what site you are parsing, but this: [sitename].com/?[pagename].do/ is not something I would call default Struts behaviour, assuming it's indeed a Struts application.
Having a .do extension was indeed something Struts used to use as request mapping, but the URL in that case should be [sitename].com/[pagename].do not [sitename].com/?[pagename].do/
In the second form, the action is in fact a parameter in a query string. This is why this syntax is broken: [sitename].com/?[pagename].do?[name]=[value]&[name]=[value]. You want to send a query string to the action but the action itself is a parameter in the query string.
But that's not the issue. The issue is that the site is doing something with that parameter and expects to receive it's data in a certain way, a way you were not able to reverse engineer.
Assuming again that this is a Struts application, Struts uses a front controller to intercept all action.do URLs and then use the action to invoke a particular class in the application, a class that is mapped to that particular action. The format for this should be [sitename].com/[pagename].do. That would be similar to having, say, [sitename].com/[pagename].php.
But having the action as a parameter makes me think that the site has a different front controller (not that of Struts) that is taking the parameter from the query string and passing it downstream to the Struts framework.
There could be a lot of reasons for having this funky way of handling requests, including making it harder for others to scrape the site, although this seems kinda straight forward:
$.post("/?dumps.do/", {s: id, pg: 2}, ...
Have you tried doing a POST to the root of the application with the action in the query string?

Pass parameter from 1 page to another using post method

I have a page "Demo.aspx". I need to set some parameters using post method and redirect the page to "DemoTest.aspx".
Is there any way to set parameters in post method in asp.net? I don't want to set "Querystring" due to security propose.
Also I need server side code for this. I am not able to use "Javascript" or "Jquery" for the same.
Here is some more description for the same.
Right now I am using Response.Redirect("www.ABC.Com/DemoTest.aspx?P1=2"). So the page is simply redirect to the given URL.
Now I don't want to pass that "P1" in "Querystring". Instead of query string I want to use Post method.
Please note that redirection page is not in my own application. So I cant maintain session or "Viewstate".
Thanks in advance.
Use a session variable and response.redirect to the next page.
Session["MyVariable"] = "someThing";
Response.Redirect("DemoTest.aspx");
The value stored in Session variables will be accessible across application.
you can store in session like this :
Session["id"] = "anyID";
To get values On another page you need to write
string id = Convert.ToString(Session["Id"]);
However
By default, in .NET pages post() do the things automatically.
You will need to do sumthing like this:
Server.Transfer("DemoTest.aspx", True)

Url Routing Question multiple departments

I want my url to look like this www.website.com/browse/computers/consoles/playstation-3/en-NZ.aspx. The part where it starts - browse which I guess is my controller - computers/consoles/playstation-3 is my action and - en-NZ.aspx is the page I want to name it. My three questions are how do you set up the action part when there are multiple departments and what is the regular expression for en-NZ for the CultureInfo is it /\{2, [a-z]}\-\{2, [A-Z]} I also need that expression to have it for two lower case letters for turkey e.g tr wich is the only language code with two letters. And how do you access a particluar department in the url after the {browse}/{*multipleDepartments}/ part.
void RegisterRoutes(RouteCollection routes)
{
routes.MapRoute(
"browse", //Name of the Route (can be anyuthting)
"{*departments}/regexp goes here.aspx", // parameters not to sure about the*
"~/Departments.aspx"); //Page which will handles and process the request
}
check my comments
Also I have created a CTE Expression which createds the Url for me it builds a link like the example above /computers/consoles/playstation-3 if I have to put that in parameters how Do i deal with that in a parameters url, what I mean is the parameters would be multiple on the same query like Departments.aspx?a=computersb=consoles&c=playstation-3. I wouldn't know how deep the query is so what do I do if it's in this case dealing with parameter.
I think you are going about this the wrong way... the culture info shouldn't be the page name, it should be part of the url. You don't normally create separate pages for different languages, instead you use resources to localise a page.
With URL routing, generally the make-up of a route follows the pattern {controller}/{action}/{id}.
So the URL you are looking to route would look similar to this:
www.website.com/en-NZ/consoles/list/playstation-3
For further reference, check out these good tutorials:
Scott Guthrie: ASP.NET MVC Framework (Part 2): URL Routing
Stephen Walther: ASP.NET MVC Routing Overview

Parameter passing in ASP.Net MVC

i want to make some questions about asp.net mvc.Actually,i am not familiar with web developing.my questions are i have two controllers,one is login and another one is
profile.After login,i want to call profile.so,i use this way,
return RedirectToAction("DiaplayProfile","Profile",new { personID = Person.personID});
my problem is parameter that i passed are shown i URL.i don't want to show.In web developing,if we use post method to send data,parameters are not shown in url,is it correct?for me,i need to pass parameter ,but,i don't want to show at url.
How i use in post method in MVC RedirectToAction?i also tested with TempData
to pass data,but,it's gone after if i make refresh.how i hanlde this?And also,
can i use [AcceptVerbs(HttpVerbs.Post)] for solve this problem?
guide me right ways, please.
Regards
Chong
You can't do a post as part of a redirect; a redirect must be a get request since you're simply passing the browser the URL to which to redirect. In MVC, having the id as part of the URL is actually considered to be a good thing. I would embrace it. Rather than having the parameter be personID, I would use id so that the default routing can be used. Eventually I'd want to end up with a URL that looks like:
http://example.com/profile/display/1345
where 1345 is the id of the person in question. If you use default routing, that would mean that you have a ProfileController with a Display method that takes a single id parameter (of type int). You would redirect to it using:
return RedirectToAction( "display", "profile", new { id = 1345 } );
BTW, you can't use the AcceptVerbs attribute to control how a redirect is made, only to control what HTTP verbs the action will respond to. In this case, I think you really do want to accept a GET and I think you really do want to have the id in the URL.

Resources