Currently trying to augment the search of an existing ASP.NET site. My background is Java, so if I was writing a server in Java, I could just handle the incoming request as a string and parse it however I wanted, taking out the search terms, etc.
What part of ASP handles that? Where should I be looking for where the incoming string is taken apart to handle the search request? There is a search button which redirects the page to a URL which includes the search parameters. That's where the trail goes cold for me as I need to know where it comes back into the server.
For example, once you've vetted the search term it gets submitted like this:
Response.Redirect("~/shop?" + type + "=" + searchBoxContent);
'type' is the type of search so that could be based on brand or searching within the product description, etc.
The site is already using some type of url rewriting as the url doesn't show up with any .aspx when you do a search. Should I be looking in a config file or a .master.cs file or where to point me in the right direction?
The easiest system for this is ASP.NET MVC which has a built-in Route and parameter handler.
See MSDN for docs.
Example:
{controller}/{action}/{id}
Can redirect to a Controller action:
public ActionResult Find(int id)
{ ... }
If this is not what you want, take a look at this blog article of Scott Guthrie on URL rewriting.
If you have a URL like this:
/shop.aspx?type=abc
then you can use Request.QueryString the get the value of type. This is the syntax:
Request.QueryString["type"]
For example if you want to get the value when /shop.aspx?type=abc is loaded at the first time, then you should add this code in Page_Load method inside the code behind (shop.aspx.cs):
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// assign 'type' query string to typeOfSearch
string typeOfSearch = Request.QueryString["type"];
}
}
Related
I am writing an e-commerce website using DotNetNuke, and I have ran into a problem. For example I have a module on a page that has a URL of mydomain/productType/product-pages. What I would like is to pass a query string to this page with the item number of product (lets say its name is bacon). And when page loads, I would like both the breadcrumbs and URL(at browser) to read mydomain/productType/product-pages/bacon. I have researched how to change the page title, meta description, and all that already and have tested and it works - but just cannot find a way to modify the URL. I don't even know if this is possible. My goal is to not create all the pages for products within DNN, because this will change over time. I'm pretty sure I can create a page within DNN each time page is passed the query string which is a possibility, and another possibility would be have my other module create the link like it should read(just no page created) and DNN would just land on product-pages just add the /bacon? But I would rather just spoof the URL if possible.
Any suggestions or help would be greatly appreciated, and Thanks for reading.
Below is code snippet for changing the title and description:
protected void Page_PreRender(object sender, EventArgs e)
{
string pageName = Request.QueryString["pageName"];
if (!string.IsNullOrEmpty(pageName))
{
Page.Title = pageName;
Page.MetaDescription = "Blah";
Page.MetaKeywords = "Stuff,more stuff";
var url = HttpContext.Current.Request.RawUrl;
//Page.ResolveUrl(url + "/" + pageName);//this didnt work
//below is another way compared to top
//DotNetNuke.Framework.CDefault myPage = new
DotNetNuke.Framework.CDefault();
//myPage = (CDefault)this.Page;
//myPage.Title = "This is the new title";
}
}
The best way to manipulate the URLs for your custom module is by building a Extension URL provider. But you need to reverse your thinking about the problem. You don't want an ugly URL with a querystring argument to change into another URL. Rather, you start with the desired URL path and you want that to resolve or be "written" as the ugly querystring URL under the covers. That's what a Extension URL provider does.
I have a tutorial on DNNHero.com that walks you through it.
https://www.dnnhero.com/video/introduction-and-url-rewriting-basics
Unfortunately, that video is behind a paywall. (IMHO, it is worth the cost even for this one tutorial and code.)
You can also check out the blog:
https://www.dnnsoftware.com/wiki/extension-url-providers#:~:text=An%20Extension%20URL%20Provider%20is,and%20logic%20to%20be%20implemented.
I am working on one application it's like twitter.
So how can I accomplish the url such as,
twitter.com/username
This will open profile related to username.
I am creating using asp.net.
Thank you
If you are planning on using MVC Razor, it will be as simple as passing a query string parameter to your page. For example:
public ActionResult Index(string name)
{
//Get user information and pass to view
User userDetails = SomeLogic.GetUser(name);
return View(userDetails);
}
Or, if using ASP.NET Web Forms you will have to use Friendly URL's by adding a Nuget package. Tutorial can be found here: http://blogs.technet.com/b/southasiamvp/archive/2014/03/31/guest-post-exploring-asp-net-friendlyurls.aspx
In the grand scheme of things, all you need to do is pass a query string parameter to your page. Using the friendly URL's will help you accomplish the URL format you require.
Update
From your comment, I see you are using Web Forms, so I will modify the answer on getting a query string value. The code below won't render URL in a friendly format, but I am hoping you will then be able to modify the example based on the link I provided above.
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["name"] != null && !String.IsNullOrEmpty(Request.QueryString["name"].ToString())
{
string myNameValue = Request.QueryString["name"].ToString();
//Since you have the name in the querystring, pass value to method that retrieves the record
User userDetails = SomeLogic.GetUser(name);
}
}
So the URL will be: profile.com/profile.aspx?name=John.
But as I stated, you will need to modify the code to change the example to use Friendly URL's, that can be found in this tutorial: http://blogs.technet.com/b/southasiamvp/archive/2014/03/31/guest-post-exploring-asp-net-friendlyurls.aspx
I need to change the URL on my address bar.
I looked for URL Rewrite but as far as I've seen it works for a request like this:
url.com/mypage.aspx?xp=asd&yp=okasd
and transforms that into:
url.com/mypage/asd/okasd
http://www.iis.net/downloads/microsoft/url-rewrite
That's not my scope. I already have MVC Routes working with url.com/mypage. The problem is that when I type that URL I am redirected (that's the behavior I want) to url.com/otherpage/actionX?param=value. The problem is that I still want the address bar to show url.com/mypage. Will URL Rewrite work for that?
I am asking because I don't know if it will work since it's an internal redirect (RedirectToAction) instead of a 'regular' access.
In case someone wonders why I can't make a route for that, as explained in my question I alread have one rule for that url.com/mypage that redirects to a 'router' which decides what action to call.
I've seen some questions, but I don't think they cover my specific problem:
MVC3 change the url
C# - How to Rewrite a URL in MVC3
UPDATE
This is my route:
routes.MapRoute(
"Profile", // Route name
"{urlParam}", // URL with parameters
new { controller = "Profile", action = "Router" } // Parameter defaults
);
Inside Router action I redirect to the correct action according to some validation done on urlParam. I need this behavior since each action returns a different View.
Updated my tags since I am now using MVC4
Thanks.
I once had to run a php site on a windows box. On the linux box it originally ran, it had a rewrite defined to make site process all request in only one php file (index.php).
I've installed and configured URL Rewrite with following parameters
Name : all to index.php
Match URL ------------------------------
Requested URL : Matches the Pattern
Using : Regular Expressions
Pattern : (.*)
Ignore Case : Checked
Conditions -----------------------------
Logical Grouping : Match All
Input : {REQUEST_FILENAME}
Type : Is Not a File
Action ---------------------------------
Action Type : Rewrite
Action Properties:
Rewrite Url : /index.php?$1
Append Query String : Checked
Log Rewritten URL : Checked
this makes all requests to site (except files like css and js files) to be processed by index.php
so url.com/user/1 is processed on server side as url.com/index.php?/user/1
since it works on server side client url stays same.
using this as you base you can build a rewrite (not a redirect).
Server.Transfer is exactly what you need, but that is not available on MVC.
On the MVC world you can use the TransferResult class defined in this thread.
With that... you add code to your ROUTE action that process the urlParam as always and instead of "redirecting" (RedirectToAction) the user to a new URL, you just "transfer" him/her to a new action method without changing the URL.
But there it a catch (I think, I have not tested it)... if that new page postbacks something... it will NOT use your router's action URL (url.com/mypage), but the real ACTION (url.com/otherpage)
Hope it helps.
In my opinion,you can try following things:
Return EmptyResult or RedirectResult from your Action method.
Also,you need to setup and construct outbound route for URL that you required.
Secondly, if these didn't work,the crude way to handle this situation is with Div tag and replacing the contents of Div with whatever HTML emitted by Action method. I am assuming here that in your problem context, you can call up jquery ajax call.
Hope this Helps.
The problem you have is that you redirect the user ( using 302 http code) to a new location, so browser ,reloads the page. you need to modify the routes to point directly to your controller. The route registration should be routes.MapRoute("specific", "my page", new { controller = "otherpage", action="actions", param="value"}).
This route should be registered first
It's simple enough to grab the current URL with
HttpContext.Current.Request.Url.ToString();
In fact, that's the accepted answer to this very similar question.
However, I've implemented application wide error handling, and have an ErrorController that generates emails that are sent back to us when there is an unhandled exception. If I implement the code snippet above in the Error Controller, the URL I get back is something like
http://.../Error/GenericError?aspxerrorpath=/Controller/ErrorProneAction
How can I grab the url of the page that actually threw the error? That is, something more like
http://.../Controller/ErrorProneAction
According to your comment - do you have a function like void Application_OnError(object sender, EventArgs e) in your global.asax? If so, then you should be able to get the information you are looking for.
protected void Application_OnError(object sender, EventArgs e)
{
var app = (MvcApplication)sender;
var context = app.Context;
string path = context.Request.PathWithQueryString;
...
Gives you something like /controllerOrRoute/action?query=val. Or you can use the RawUrl, or Url property to get basically the same thing. I just fired my application up to see what it generates and it looks like this is what you're asking for.
Edit: I should note that I tested the above for MVC3.
See this blog post:
http://blog.gauffin.org/2011/11/how-to-handle-errors-in-asp-net-mvc/
If you pass a parameter to your ActionResult, this will take the value of the aspxerrorpath query string value.
public ActionResult NotFound(string url)
{
var originalUri = url ?? Request.QueryString["aspxerrorpath"] ?? Request.Url.OriginalString;
}
Hello to all developers,
I am trying to find some example of Dynamically generate URL(PURL).
I have seen one software which generate personalised URL from MySQL database .
The only thing is that software is using PHP to generate URL and as a .NET developer I dont know about php.
My question is is there a way that I can fetch data from data base and using perticular field i can generate url which is not actually store in my web space..
eeg.
-----database-----
firstname | lastname ....
===========================
xyz abc
pqwert qweoiuy
alfa beta
the URL should be like
http://something.com/somepersonal/xyz_abc.aspx
http://something.com/somepersonal/pqwert_qweoiuy.aspx
http://something.com/somepersonal/alfa_beta.aspx
It is something like personalised page for users or clients.
I have template to use as back page but dont know how to plug and dynamically generate URL..
You're thinking of this a little backward. Generally, one wouldn't do this by generating it directly from the database. You would generally do this by routing the url batch /somepersonal/ to some personalpage control, which would then consider everything after it, like xyz_abc to be an argument. Personalpage would then use that argument to customize its display, be it from the database or wherever.
So to clarify, your URL would look something like:
http://something.com/personal/vish_soni
http://something.com/personal/colonel_gentleman
http://something.com/personal/general_specific
But all of these are being routed to Personalpage, which then uses vish_soni, colonel_gentleman, and general_specific as arguments to query the database or do whatever else it needs to do.
Microsoft has an overview of this pattern and routing in general here.
You can create a controller class and call an action method. For your case, you just need to send parameter and then lookup customer info to prepare the content.
public class HomeController : Controller
{
public ActionResult Me(string id)
{
ViewBag.Message = "Welcome to ASP.NET MVC! "+id;
var contentobj = repository.GetUSerContent(id);
return View("Index",contentobj);
}
}