Friendly URLs and Query Strings - asp.net

In my project (ASP.NET Web Forms) I want to use Friendly URLs, installed from NuGet.
I registered route in global.asax file:
Public Shared Sub RegisterRoutes(routes As RouteCollection)
routes.MapPageRoute("Route", "default/{id}", "~/default.aspx?id={id}")
End Sub
With this code, I can use default/123 instead of default?id=123. I want to add name, assigned to the id, in the url. So I can have url like this: default?123-Firstname-Lastnam. Name is saved in database, in single column. How can I add second parameter (name) to the url, add symbol - and display it without letters like this: řčš (because the application is in Chech language.
Thanks for answer.

To use FriendlyUrls, after you install it from NuGet, go to your global.asax and enable it:
Imports Microsoft.AspNet.FriendlyUrls
Public Class Global_asax
Inherits System.Web.HttpApplication
Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs)
RegisterRoutes(RouteTable.Routes)
End Sub
Sub RegisterRoutes(ByVal routes As RouteCollection)
routes.EnableFriendlyUrls()
End Sub
'rest of global
That is pretty much it. To get the values out of a URL for a page, you'll need to loop through the URL segments (don't forget Imports Microsoft.AspNet.FriendlyUrls):
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
For Each segment As String In HttpRequestExtensions.GetFriendlyUrlSegments(Request)
Dim val As String = segment
Next
End Sub
So visiting siteURL.com/default/123 will loop once and give you 123, while siteURL.com/default/122/Bilbo/Baggins will loop three times and give you 122, Bilbo, and Baggins.
Or, if you just want to use plain routing and not FriendlyUrls:
routes.MapPageRoute("id-route", "default/{id}", "~/default.aspx")
One good thing about routing is you can use the URL to pass variable data without using query strings. So the route to pass name data could look like
Sub RegisterRoutes(ByVal routes As RouteCollection)
routes.MapPageRoute("name-route", "default/{id}/{firstName}/{lastName}", "~/default.aspx")
End Sub
And then default.aspx could be hit with siteURL.com/default/123/Frodo/Baggins and has:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
Dim id As Integer = 0
Int32.TryParse(Page.RouteData.Values("id"), id)
Dim firstName As String = Convert.ToString(Page.RouteData.Values("firstName"))
Dim lastName As String = Convert.ToString(Page.RouteData.Values("lastName"))
'do something if id > 0
End Sub
Other Considerations: If you only want name in a single column, then you can combine the firstName and lastName variables for saving. Using - as a delimeter like you show in question isn't a good idea, as people can have hyphenated names. Saving name in a single column tends to cause problems as it makes it much harder to sort by first or last name, etc.
Also it appears you will be inserting into your database from a GET command. I would think this would be much more clear to do using PUT or POST.

Related

How to link DataSet to .aspx page in asp.net

I created a DataSet named CardInfo.xsd in Visual Studio 2015 that works perfectly
When I try to show data from it using a TableAdapter (which also works fine and displays the specific query I set up), I get an error in the code behind file.
It says CardInfo is not defined and also that the TableAdapter (CardInfoTableAdapters.TableTableAdapter) is not defined.
However it lets me select any other .xsd or .mdf files in the project, so I feel like the DataSet is not broadcasting itself to the rest of the project.
In the end it is supposed to get the value from the text box and show the row whose primary id matches the inputted number.
Here is the code to create the DataSet on the page:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Page.IsPostBack Then
GetCardInfo(cardentry.Text)
End If
End Sub
Protected Sub GetCardInfo(ByVal Entry As String)
Dim myDataSet As New CardInfo
Dim cardDA As New CardInfoTableAdapters.TableTableAdapter
cardDA.Fill(myDataSet.Entry, Entry)
GridViewRetrieval.DataSource = myDataSet.Tables("Table")
GridViewRetrieval.DataBind()
End Sub

How to share a variable value with a webmethod?

I have this code:
Dim main_id As int
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
main_id =1
End Sub
<WebMethod()> _
Public Shared Function BindPersonnel(ByVal product_id As String) As String
Dim project_id AS int16
project_id=main_id 'this doesn't work
End Function
On page load, I set the value of variable main_id and I need a way to somehow share the main_id with webmethod function, how can this be done? I have not tried session variable and I don't want to use session variable. I found this link Accessing a common variable in WebMethod and jQuery but I can't figure out how this is going to solve my problem. I also read some posts about using hidden field, which requires me to go two trips. I would love to avoid that.
WebMethods are independent of the other variables on the page. If you want to access main_id, you could declare it as Private Shared main_id As Integer, but that would then cause all of your users to have access to the same ID value, which you probably don't want.
Perhaps the easiest way to do this is to store the value in SessionState, and enable sessionstate access in the WebMethod. On the other hand, this removes the asynchronous-like functionality that you are looking for (it may not be an issue).
SessionState will give you the ability to have a per-session value (avoiding the use of the Shared solution mentioned above).
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Session("main_id") = 1
End Sub
<WebMethod(EnableSession:=True)>
Public Shared Function BindPersonnel(ByVal product_id As String) As String
Dim project_id As Integer = CInt(HttpContext.Current.Session("main_id"))
End Function

Routing in ASP.Net web app

I am trying to use a single RouteURL to route to different pages dependent on the Route name but when I click on a button within my aspx page the page gets routed back to itself:
Here is what I have in my Global.asax
Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs)
' Code that runs on application startup
RegisterRoutes(RouteTable.Routes)
End Sub
Private Sub RegisterRoutes(ByVal routes As routecollection)
routes.MapPageRoute("1", "test", "~/default1.aspx")
routes.MapPageRoute("2", "test", "~/default2.aspx")
routes.MapPageRoute("3", "test", "~/default3.aspx")
End Sub
And here is what I have put in my default1.aspx page:
Protected Sub Button1_Click(sender As Object, e As System.EventArgs) Handles Button1.Click
Response.RedirectToRoute("2")
End Sub
Can anyone point me in the right direction please?
You have duplicated your routeUrl values in your mapped routes. What's happening is that it is routing to your second route, as found by name "2", but that route is http://yoursite/test, which, when it then processes the request, is matching to the first route entry, or default1.aspx.
You can't use the same routeUrl (i.e., "test"), for all of your mappings.
Further reading: ASP.NET Routing
An example of how you could change it:
Private Sub RegisterRoutes(ByVal routes As routecollection)
routes.MapPageRoute("2", "test/2", "~/default2.aspx")
routes.MapPageRoute("3", "test/3", "~/default3.aspx")
routes.MapPageRoute("1", "test/{*whatever}", "~/default1.aspx")
End Sub
Note in this example that route "1" is at the bottom. This is because routes are matched top-down, so more restrictive matches should be listed first. In this example yourdomain/test/2 will goto default2.aspx, yourdomain/test/3 will goto default3.aspx, and default1.aspx will essentially be the default, catching yourdomain/test, yourdomain/test/4, yourdomain/test/5, etc.

How can I grab the current url and assign it to a variable using vb and asp.net?

I have a form that the user fills out and submits. I have vb code that converts that form into an email and sends it to me. I need to know what page it is coming from so I want to assign the current url to a variable that will be included in the email.
Simply put: How do I assign the URL to a variable?
You can find this in the request object. e.g. Request.Url.AbsoluteUri
Dim url As String = Request.Url.AbsoluteUri
VB.NET
'static variable
Private Shared prevPage As String = String.Empty
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If (Not IsPostBack) Then
prevPage = Request.UrlReferrer.ToString()
End If
End Sub

Preserve Data-structure on AJAX postback

Partial Class ClientCenter_UpdateSub
Inherits System.Web.UI.Page
Structure PInfo
Dim Name As String
Dim Surname As String
End Structure
Dim OldPInfo As New PInfo
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
'blah blah
OldPInfo.Name = Dt.Rows(0).Item("Name").ToString
OldPInfo.Surname = Dt.Rows(0).Item("Surname").ToString
end if
end sub
End Class
The first time the page loads my structrure is filled correctly.
After an AJAX postback all the structure fields are setting to nothing. (It seems that the Dim OldPInfo As New PInfo is called again), but i should better ask the SO Experts.
So anyway, what am i doing wrong here?
First off, You should never assign a variable outside of a property or a method.
Second, web applications are stateless (which means NOTHING is automatically saved from call to call - unless you store it somewhere like Viewstate, Session, etc.).
Remember to accept this answer if it helps solve your problem.

Resources