Reputation: 1011
I am working on an asp.net application where I am using Url Rewriting. My webpage name is NewsDetail.aspx whose Code is:
<asp:Content ContentPlaceHolderID="ContentPlaceHolder1" ID="Content1" runat="server">
<div style="min-height: 150px; padding: 10px 10px;">
<marquee behavior="scroll" direction="up" scrollamount="2" height="150">
<asp:ListView ID="listNews" runat="server">
<ItemTemplate>
<p>
<a href="NewsDetail.aspx?ID=<%#Eval("ID") %>"> <%#Eval("Title") %> </a>
</p>
</ItemTemplate>
</asp:ListView>
</marquee>
</div>
</asp:Content>
I have Bind This Listview in Default.aspx WebPage Page-Load Event as:
DataTable dt = new DataTable();
dt = new Process_News().SelectPublishNews();
if (dt.Rows.Count > 0)
{
listNews.DataSource = dt;
listNews.DataBind();
}
I want that when user clicks on an item in "listNews" Listview then it should be Redirected to NewsDetail.aspx WebPage.If user Click on item whose ID=1 Then the Addressbar is showing
http://AtharvaJournal.com/NewsDetail.aspx?ID=1
But I want to show as http://AtharvaJournal.com/News/1
For this i have done following code in global.asax file:
void RegisterRoutes(RouteCollection routes)
{
routes.MapPageRoute("News", "News/{Id}", "~/NewsDetail.aspx");
}
protected void Application_Start(object sender, EventArgs e)
{
RegisterRoutes(RouteTable.Routes);
}
In NewsDetail.aspx Page I have done following Code:
if (!string.IsNullOrEmpty(Page.RouteData.Values["Id"].ToString()))
{
string id = Page.RouteData.Values["Id"].ToString();
long ID = Convert.ToInt64(Page.RouteData.Values["Id"].ToString());
dt = new Process_News().SelectByID(ID);
if (dt.Rows.Count > 0)
{
hTitle.InnerText = dt.Rows[0]["Title"].ToString();
PDetail.InnerText = Server.HtmlDecode(dt.Rows[0]["Contents"].ToString());
}
}
Now when I write following thins in my addressbar : ( http://AtharvaJournal.com/News/1) Then It runs well,But when i directly click on any item in "listNews" ListView Then It shows the exception as:-
"Object reference not set to an instance of an object"
Please Help me Here.
Upvotes: 0
Views: 1527
Reputation: 1011
I Found a better way to solve this problem. In ListView named "listnews" following code was written inside itemtemplate:-
<a href="NewsDetail.aspx?ID=<%#Eval("ID") %>"> <%#Eval("Title") %> </a>
I modified it as
<a href="News/<%#Eval("ID") %>"> <%#Eval("Title") %> </a>
Now it is working well and good for me.
Upvotes: 1
Reputation: 156978
You have two problems:
First, your (second) url does not use the routing table, change the url to http://AtharvaJournal.com/News/THE_ID
there too.
Or use this to get the Id for the url without url mapping:
Request.QueryString["Id"]
Second, you are checking Page.RouteData.Values["Id"].ToString()
while Page.RouteData.Values["Id"]
is null.
Try this instead:
(string)Page.RouteData.Values["Id"]
Upvotes: 2