SEO friendly URl in asp.net - c#

Im creating a web application. There are a default page where a list of questions. When user click the question that will redirect to the user to ViewQuestion that is in the Question folder. At the default.aspx page im using the datalist control to display question title . And there i am generating the url with id to the question . For this code is below .
protected void listQuestion_ItemDataBound(object sender, DataListItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item ||
e.Item.ItemType == ListItemType.AlternatingItem)
{
LinkButton lnkTitle = (LinkButton)e.Item.FindControl("lnkQuestion");
// lnkTitle.Style.Add("text-decoration", "none");
PostEntity Item = (PostEntity)e.Item.DataItem;
lnkTitle.PostBackUrl = GenerateURL(Item.Title, Item.Id);
}
}
public static string GenerateURL(string title, int Id)
{
string strTitle = title.Trim();
strTitle = strTitle.ToLower();
//strTitle = strTitle.Replace();
strTitle = strTitle.Replace(" ", "-");
strTitle = strTitle.Trim();
strTitle = strTitle.Trim('-');
strTitle = "~/Questions/ViewQuestion.aspx?QuestionID=" + Id.ToString().Trim() + "/" + strTitle + ".aspx";
return strTitle;
}
in global.asax the code is
void Application_Start(object sender, EventArgs e)
{
// Code that runs on application startup
RegisterRoute(RouteTable.Routes);
}
static void RegisterRoute(RouteCollection route)
{
route.MapPageRoute("Default", "Default", "~/Default.aspx");
route.MapPageRoute("ViewQuestion", "Questions/ViewQuestion{QuestionID}", "~/Questions/ViewQuestion.aspx");
}
And the viewpage to get the Querystring as below :
lblQustionText.Text = this.Page.RouteData.Values["QuestionID"].ToString() as string; // giving me object reference exception
my pageurl is generating like this
/Questions/ViewQuestion.aspx?QuestionID=1376/get-the-current-logged.aspx
How can i make this example for SEO friendly url . Thanks for your answer.

There are two things about your code that seem to be wrong:
Your page route should probably include a forward slash between the page name (ViewQuestion) and the question ID:
Questions/ViewQuestion/{QuestionID}
The page URL you generate does not match the route, it should not contain the aspx suffix and the order of the route parameter and the query parameter is mixed up. It should be something like
String.Format("~/Questions/ViewQuestion/{0}?QuestionID={1}", strTitle, Id.ToString().Trim())
As a sidenote, I find it a bit confusing that you include a query parameter with the exact same name as your route parameter. My advice would be to use a route parameter for both, stackoverflow-style:
/Questions/ViewQuestion/numerical-id/question-description

Related

Is this a good way to pass variables between asp.net pages

It's the first time I'm passing variables between two pages in my asp.net project.
It works, but I'm wondering if it is a good way to do it? Is it secure? Is there a better way?
The reason why I ask is that I've have learned never to use concatenation in sql, but instead use parameters (which I always do from now on). Is there a similar risk in this case?
In web page1:
protected void Button1_Click(object sender, EventArgs e)
{
string email = txtEmail.Text;
string date = txtDate.Text;
string time = txtTime.Text;
string name = txtName.Text;
string url = "~/change.aspx?newemail="+mail+"&newdate="+date+"&newtime="+time+"&newname="+name+"";
Response.Redirect(url);
}
In web page2:
protected void Page_Load(object sender, EventArgs e)
{
String email = Request.QueryString["newemail"];
String date = Request.QueryString["newdate"];
String time = Request.QueryString["newtime"];
String name = Request.QueryString["newname];
TextBox1.Text = email;
TextBox2.Text = date;
TextBox3.Text = time;
TextBox4.Text = name;
}
if it is a good way to do it?
Not really. You need to url encode the values because if they contain special characters the receiving page will not parse them correctly:
string url = "~/change.aspx?" +
"newemail=" + HttpUtility.UrlEncode(mail) +
"&newdate=" + HttpUtility.UrlEncode(date) +
"&newtime=" + HttpUtility.UrlEncode(time) +
"&newname=" + HttpUtility.UrlEncode(name);
Is it secure?
No, not at all. Anyone could send a request to your target page with whatever values he feels good for him.
Is there a better way?
That would depend on your specific requirements and whether the information you are transmitting is sensitive or not. If it is sensitive information, then you might consider storing the values on the server instead of passing them as query string parameters. For example you could use the ASP.NET Session for this purpose.
Is it secure? No, of course not, the values are on the query string which gets sent to the browser. If you want to keep it secure put the values in session on the server side.
You are using QueryString Way to pass variables from one page to another page.its not a problem if the parameters are not secure like you cant pass secure info(Sensitive Information) like passwords,any important ids...
if you want to handle with secure parameters(Sensitive Information) you can use Sessions,Cookies..
In your case you are passing names.i hope it doesnt create any problems because this are not secure parameters(Sensitive info).even though if you feel any security risks you can use encryption and decryption concepts like encrypt your parameter name and pass it with url and then decrypt that parameter where you want to use.
Refer :
http://msdn.microsoft.com/en-us/library/6c3yckfw%28v=vs.100%29.aspx
http://www.codeproject.com/Articles/8055/Transferring-page-values-to-another-page
For better understanding about passing variables from one page to another page
Thank you guys for you help!
I have now changed it to Sessions. My code now looks like this:
In web page1:
string email = txtEmail.Text;
string date = txtDate.Text;
string time = txtTime.Text;
string name = txtName.Text;
Session["email"] = email;
Session["date"] = date;
Session["time"] = time;
Session["name"] = name;
Response.Redirect("~/change.aspx");
In web page2:
protected void Page_Load(object sender, EventArgs e)
{
string email = (string)(Session["email"]);
string date = (string)(Session["date"]);
string time = (string)(Session["time"]);
string name = (string)(Session["name"]);
TextBox1.Text = email;
TextBox2.Text = date;
TextBox3.Text = time;
TextBox4.Text = name;
}

Windows Phone 7 passing data from listbox to another page via context query string

Hi there I am a beginner with developing on C#. I am having some problems passing data from one page to another. Within a listbox I have data which i have obtained from a database via web service.
I have created some coding to move sets of selected data to the next page and input it into the assigned text blocks. Currently this coding only works for one data field "eventId."
Could you please have a look at my code and tell me what I have done wrong and how i can fix this.
Here is my coding from the page which holds the listbox with the sets of data:
private void FirstListBox2_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
EventServiceReference1.Event myEvent = (EventServiceReference1.Event)FirstListBox2.SelectedItem;
int eventId = myEvent.EventID;
string eventList = myEvent.EventList;
string eventDescription = myEvent.Description;
string eventDate = myEvent.Date;
string eventTime = myEvent.Time;
string eventLocation = myEvent.Location;
var url = string.Format("/EventPageTemp.xaml?eventId={0}", eventId + "&eventList={0}", eventList);
NavigationService.Navigate(new Uri(url, UriKind.Relative));
}
Here is my coding from the "EventPageTemp" page which i am passing the data to:
int eventId;
string eventIdStr;
string eventList;
if (NavigationContext.QueryString.TryGetValue
("eventId", out eventIdStr) && int.TryParse(eventIdStr, out eventId))
{// load event data, and set data context
txtEID.Text = eventIdStr;}
if (NavigationContext.QueryString.ContainsKey("eventList"))
{
string val = NavigationContext.QueryString["eventList"];
txtEList.Text = eventList;
}
At the moment it is coming up with the errors:
- the name 'eventList' does not exist in current context
-use of unassigned local variable 'eventList'
Please can you help me figure this out. Thank you.
the issue is your url, eventId + "&eventList={0}", eventList will be pass as eventId:
var url = string.Format("/EventPageTemp.xaml?eventId={0}", eventId + "&eventList={0}", eventList);
it should be:
var url = string.Format("/EventPageTemp.xaml?eventId={0}&eventList={1}", eventId, eventList);

URL where user come from ASP.Net but have NULL

I want to know-from what url user come from.
So, i use
Uri MyUrl = Request.UrlReferrer;
But when i get only null value from MyUrl:
I have two projects-first is my aspx page, second- redirects to this first project-page with GET parameters.
But when second project redirect to first project- i have :
Object reference not set to an instance of an object.
My second test project so simple:
protected void Page_Load(object sender, EventArgs e)
{
Response.Redirect("http://localhost:54287/go.aspx?id=DEFAULT");
}
First and main project:
protected void Page_Load(object sender, EventArgs e)
{
//Request.ServerVariables('http_referer');
// Request.ServerVariables;
string id = Request.QueryString["id"];
if (id != null)
{
Uri MyUrl = Request.UrlReferrer;
Console.WriteLine(MyUrl);
Response.Write("Referrer URL : " + MyUrl.AbsolutePath);
}
}
Error in :Response.Write("Referrer URL : " + MyUrl.AbsolutePath);
OK, there a a few errors:
Your code:
Uri MyUrl = Request.UrlReferrer;
Console.WriteLine(MyUrl);
Response.Write("Referrer URL : " + MyUrl.AbsolutePath);
In the code above you get a NullReferenceException because MyUrl is null.
The UrlReferer may be null, so you have to check this like:
Uri MyUrl = Request.UrlReferrer;
Console.WriteLine(MyUrl);
if (MyUrl != null)
Response.Write("Referrer URL : " + MyUrl.AbsolutePath);
Also you can never make sure that the UrlReferer can have a value, if the user comes from another website you don't know if this website will provide this value, so you have first to assume the referrer is null (in summary never trust it).
Second, when you use Response.Redirect on your code ran server-side you don't know what is the referrer.
I find this question and this question that will help you to better understand.
UrlReferrer is based off the HTTP_REFERER header that a browser should send. But, as with all things left up to the client, it's variable.
I know some "security" suites (like Norton's Internet Security) will strip that header, in the belief that it aids tracking user behavior. Also, I'm sure there's some Firefox extensions to do the same thing.
Bottom line is that you shouldn't trust it. Just append the url to the GET string and redirect based off that.
Reference:
Stackover flow reference

WP7 passing multiple pieces of data between pages

In my app I am building my own media player. When a user selects a song to play want to be able to pass the link to the sample media and the metadata associated with it (Artist, Track, Album Art, etc.) The part I'm stuck on is how to group all the data and pass it to the media player page. Here's what i have so far.
Determine what item was selected and add data to query string.
UPDATED
public void musicSampleSelectedHandler(object sender, RoutedEventArgs e)
{
Track selected = (sender as Image).DataContext as Track;
ListBoxItem pressedItem = this.listReleaseMain.ItemContainerGenerator.ContainerFromItem(selected) as ListBoxItem;
if (pressedItem != null)
{
string _rT = selected.title;
string _rN = selected.release.name;
//string _rA = selected.artists; ????
string _rI = selected.images.large.url;
string _rS = selected.sampleUrl;
this.NavigationService.Navigate(new Uri("/Pages/MediaPage.xaml?releaseName=" + _rN + "&releaseTrack=" + _rT + "&releaseImage=" + _rI
+ "&releaseSample=" + _rS, UriKind.Relative));
}
}
OnNavigatedTo method to pull data out of the query string
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
base.OnNavigatedTo(e);
string releaseName = String.Empty;
string releaseImg = String.Empty;
string releaseUrl = String.Empty;
if (NavigationContext.QueryString.TryGetValue("releaseUrl", out releaseUrl))
{
sampleMedia.Source = new Uri(releaseUrl, UriKind.Absolute);
}
}
I'm not sure if I can use the query sting to pass multiple pieces to the media player, or if I to do something different to pass the data to the other page. All of my data comes from the web using a webclient. Thanks for the help.
QueryString is just a Dictionary of the parameters passed in via the Uri. The Uri uses the standard syntax of passing in parameters delimited by &. So in your example, if you had something like:
this.NavigationService.Navigate(new Uri("/Pages/MediaPage.xaml?releaseUrl=" + releaseUrl + "&releaseImg=" + releaseImg , UriKind.Relative));
then you can then parse this out using something like:
if (NavigationContext.QueryString.TryGetValue("releaseUrl", out releaseUrl))
{
sampleMedia.Source = new Uri(releaseUrl, UriKind.Absolute);
}
if (NavigationContext.QueryString.TryGetValue("releaseImg", out releaseImg))
{
// do something with releaseImg
}

How to make a function into a class or module in c#

I am just learning how to use classes in my projects. I have been working on a DataAccessClass.cs and am doing well (I think).
Taking a break from data access, I decided to try to make a void into a class. This void sends a message to the client as a javascript alert. It works well, but has to be included on each page. When I tried to make it a class, I was informed that my class does not contain a definition for ClientScript. I included all the "using" directives from the original page to no avail... Any hints or suggestions would be greatly appreciated.
The original code:
//------------------------------------------------------------------------------
//Name: SendErrorMessageToClient
//Abstract: show alert on client side
//------------------------------------------------------------------------------
protected void SendErrorMessageToClient(string strErrorType, string strErrorMessage)
{
string strMessageToClient = "";
//Allow single quotes on client-side in JavaScript
strErrorMessage = strErrorMessage.Replace("'", "\\'");
strMessageToClient = "<script type=\"text/javascript\" language=\"javascript\">alert( '" + strErrorType + "\\n\\n" + strErrorMessage + "' );</script>";
this.ClientScript.RegisterStartupScript(this.GetType(), "ErrorMessage", strMessageToClient);
}
Messages are sent into this void like this:
if (DataAccessClass.OpenSqlConnection(ref Conn, strConn, out strErrorMessage) == false)
{
string strErrorType = "Database Connection Error:";
SendErrorMessageToClient(strErrorType, strErrorMessage);
}
Or this:
catch (Exception excError)
{
string strErrorType = "Unhandled Exception:";
string strErrorMessage = excError.Message;
SendErrorMessageToClient(strErrorType, strErrorMessage);
}
You are receiving the error as 'Clientscript' is a property derived from a System.Web.UI.Page and by moving into a separate class file, you no longer have access to this property.
You could solve this by passing in the page as well, and amending the code to
protected void SendErrorMessageToClient(string strErrorType, string strErrorMessage, Page page)
{
string strMessageToClient = "";
//Allow single quotes on client-side in JavaScript
strErrorMessage = strErrorMessage.Replace("'", "\\'");
strMessageToClient = "<script type=\"text/javascript\" language=\"javascript\">alert( '" + strErrorType + "\\n\\n" + strErrorMessage + "' );</script>";
page.ClientScript.RegisterStartupScript(this.GetType(), "ErrorMessage", strMessageToClient);
}
ClientScript Property is part of the Page class that every ASPX page inherit from. Therefore you can not just use it from inside your class unless it (i.e. your class) has Page as its base class.
this. is for fields in your method in classes.
Why do you want to make this a class? It shouldn't be a class, it doesn't have any properties or fields, unless you can think of one. You do understand if you make it a class you would still have to intialize it on every page.
You could make it a static string method you would still have to include this on every page.
this.ClientScript.RegisterStartupScript(this.GetType(), "ErrorMessage", strMessageToClient);
You'll need to pass the page into the function
SendErrorMessageToClient(Page page, string strErrorType, string strErrorMessage)
so that you can change
this.ClientScript...
to
page.ClientScript...
The reason being that ClientScript is part of the Page class
Or, possibly better, pass the ClientScript object, rather than page.
So your definition would look like
SendErrorMessageToClient(ClientScript clientScript, string strErrorType, string strErrorMessage) {
string strMessageToClient = "";
//Allow single quotes on client-side in JavaScript
strErrorMessage = strErrorMessage.Replace("'", "\\'");
strMessageToClient = String.Format("<script type='text/javascript' language='javascript'>alert('{0}\\n\\n{1}');</script>",
strErrorType, strErrorMessage);
clientScript.RegisterStartupScript(this.GetType(), "ErrorMessage", strMessageToClient);
}

Categories