Asp.net MVC 4 Multiple Route - asp.net

I'm beginer in asp.net mvc. I try the routing. but all route formats using by first defined route value. Example all views url finishing with "index" i don't want this url format. and i want localhost:56609/Cuisines/Detail/4/thai but program showing localhost:56609/Cuisines/getCuisineDetail/6/thai . How to do this explain me please.
RouteConfig
routes.MapRoute( _
name:="RestaurantDetail", _
url:="{controller}/{action}/{id}/{title}", _
defaults:=New With {.controller = "Restaurants", .action = "Index", .id = UrlParameter.Optional, .title = UrlParameter.Optional} _
)
routes.MapRoute( _
name:="Cuisines", _
url:="{controller}/Detail/{id}/{title}", _
defaults:=New With {.controller = "Cuisines", .action = "getCuisineDetail", .id = UrlParameter.Optional, .title = UrlParameter.Optional} _
)
routes.MapRoute( _
name:="Default", _
url:="{controller}/{action}", _
defaults:=New With {.controller = "Home", .action = "Index"} _
)
View
#<p>#Html.ActionLink(Model(i).Name, "getCuisineDetail", New With {.id = Model(i).CusineID, .title = OnlineSiparis.UrlEditor.CheckUrl(Model(i).Name)}) </p>

The "RestaurantDetail" route also matches the URL pattern of the more specific "Cuisines" route. Try to change the code so that "Cuisines" is mapped first...
routes.MapRoute( _
name:="Cuisines", _
url:="{controller}/Detail/{id}/{title}", _
defaults:=New With {.controller = "Cuisines", .action = "getCuisineDetail", .id = UrlParameter.Optional, .title = UrlParameter.Optional} _
)
routes.MapRoute( _
name:="RestaurantDetail", _
url:="{controller}/{action}/{id}/{title}", _
defaults:=New With {.controller = "Restaurants", .action = "Index", .id = UrlParameter.Optional, .title = UrlParameter.Optional} _
)

Related

If statement using SqlDataReader value not working

I am working on a cart/basket page of an e-commerce site. Specifically: "-" link button to decrease quantity of selected product by 1 in the cart, and later the "+" link button to increase quantity of selected product by 1 in the cart.
For the "-" button I am doing:
Check the CategoryID of the product selected.
If the CategoryID = 3 or 4, then:
Check if the quantity of the selected product is more > 1.
Quantity = Quantity - 1.
Reduce the amount of HoursWork (used for booking slot length) for the selected product.
Product Stock + 1.
Reduce the weight (used for delivery price).
Else: label displays "Quantity cannot be changed for Detailing & Valeting services.
I am using a SqlDataReader to get the CategoryID, and then storing it as Integer in variable CategoryID.
I tested by displaying the variable contents in a label, and it collects the correct CategoryID - however the "If CategoryID = "3" or "4" Then... is not working, as all categoryIDs are running the IF section or the statement and not the ELSE section.
Protected Sub lDecrease_Click(ByVal sender As Object, ByVal e As EventArgs)
'get clicked button
Dim lnk As LinkButton = CType(sender, LinkButton)
'Get clicked button row
' Dim row As GridViewRow = CType(lnk.Parent.Parent, GridViewRow)
Dim row As GridViewRow = CType(lnk.NamingContainer, GridViewRow)
'Get row selected
Dim idx As Integer = row.RowIndex
'get CartID
Dim lblCartID As Label = CType(row.Cells(0).FindControl("lblCartID"), Label)
Dim SCCartID As String = lblCartID.Text.ToString
'get ProductID
Dim lblProductID As Label = CType(row.Cells(0).FindControl("lblProductID"), Label)
Dim SCProductID As String = lblProductID.Text.ToString
'get ProductName
Dim lblProduct As Label = CType(row.Cells(0).FindControl("lblProduct"), Label)
Dim SCProduct As String = lblProduct.Text.ToString
'get Size
Dim lblSize As Label = CType(row.Cells(0).FindControl("lblSize"), Label)
Dim SCSize As String = lblSize.Text.ToString
'get Price
Dim lblPrice As Label = CType(row.Cells(0).FindControl("lblPrice"), Label)
Dim SCPrice As String = lblPrice.Text.ToString
'get Quantity
Dim lblQuantity As Label = CType(row.Cells(0).FindControl("lblQuantity"), Label)
Dim SCQuantity As String = lblQuantity.Text.ToString
'get Subtotal
Dim lblSubtotal As Label = CType(row.Cells(0).FindControl("lblSubtotal"), Label)
Dim SCSubtotal As String = lblSubtotal.Text.ToString
'get HoursWork
Dim lblHoursWork As Label = CType(row.Cells(0).FindControl("lblHoursWork"), Label)
Dim SCHoursWork As String = lblHoursWork.Text.ToString
'get Weight
Dim lblWeight As Label = CType(row.Cells(0).FindControl("lblWeight"), Label)
Dim SCWeight As String = lblWeight.Text.ToString
Dim conn As SqlConnection = New SqlConnection(ConnectionString)
' start of category check
Dim cmd4 As SqlCommand = New SqlCommand
cmd4.CommandText = "SELECT products.CategoryID FROM products INNER JOIN Cart on products.ProductID = cart.ProductID WHERE cart.productID=#ProductID"
Dim ProductID2 As SqlParameter = New SqlParameter("#ProductID", SqlDbType.Int, 4)
ProductID2.Value = SCProductID
cmd4.Parameters.Add(ProductID2)
cmd4.Connection = conn
conn.Open()
cmd4.ExecuteNonQuery()
Dim reader As SqlDataReader = cmd4.ExecuteReader
Dim CategoryID As Integer
While reader.Read()
CategoryID = CType(reader.Item("CategoryID"), Integer)
End While
'Testing CategoryID value = success
lblNoStock.Visible = True
lblNoStock.Text = CategoryID
conn.Close()
'Nest IF statement based on Category ID 1,2, cannot be reduced in Quantity
If CategoryID = "3" Or "4" Then
' Run quantity check – And update if possible
Dim exists As Boolean = False
'cart quantity
Dim cmd As SqlCommand = New SqlCommand
cmd.CommandText = "Select Quantity from Cart where CartID = #CartID"
cmd.Connection = conn
' conn.Close()
conn.Open()
'rename cart id 5
Dim CartID5 As SqlParameter = New SqlParameter("#CartID", SqlDbType.Int, 4)
CartID5.Value = SCCartID
cmd.Parameters.Add(CartID5)
'check if more than 1 in cart
exists = (CType(cmd.ExecuteScalar, Integer) > 1)
If exists Then
'show label to say no more in stock
lblNoStock.Visible = True
' lblNoStock.Text = "Available!"
conn.Close()
' update quantity & subtotal
Dim cmd1 As SqlCommand = New SqlCommand
cmd1.CommandText = "UPDATE Cart SET Quantity = Quantity - 1, Subtotal = #Subtotal - #Price WHERE CartID = #CartID"
'update hourswork
Dim cmd2 As SqlCommand = New SqlCommand
cmd2.CommandText = "UPDATE Cart SET HoursWork = (HoursWork - (Select Products.HoursWork FROM Products WHERE Products.ProductID = Cart.ProductID)) WHERE CartID = #CartID"
'UPDATE PRODUCTS STOCK + 1
'"UPDATE Products Set Stock = Stock + 1 WHERE ProductID = #ProductID"
Dim cmd3 As SqlCommand = New SqlCommand
'UPDATE weight
cmd3.CommandText = "UPDATE Cart SET Weight = (Weight - (Select Products.Weight FROM Products WHERE Products.ProductID = Cart.ProductID)) WHERE CartID = #CartID"
cmd1.Connection = conn
cmd2.Connection = conn
cmd3.Connection = conn
conn.Open()
Dim PProductID As SqlParameter = New SqlParameter("#ProductID", SqlDbType.Int, 4)
PProductID.Value = SCProductID
cmd1.Parameters.Add(PProductID)
Dim Subtotal As SqlParameter = New SqlParameter("#Subtotal", SqlDbType.Decimal, 5)
Subtotal.Value = SCSubtotal
cmd1.Parameters.Add(Subtotal)
Dim Price As SqlParameter = New SqlParameter("#Price", SqlDbType.Decimal, 5)
Price.Value = SCPrice
cmd1.Parameters.Add(Price)
Dim CartID As SqlParameter = New SqlParameter("#CartID", SqlDbType.Int, 4)
CartID.Value = SCCartID
cmd1.Parameters.Add(CartID)
Dim CartID2 As SqlParameter = New SqlParameter("#CartID", SqlDbType.Int, 4)
CartID2.Value = SCCartID
cmd2.Parameters.Add(CartID2)
Dim CartID3 As SqlParameter = New SqlParameter("#CartID", SqlDbType.Int, 4)
CartID3.Value = SCCartID
cmd3.Parameters.Add(CartID3)
Try
cmd1.ExecuteNonQuery()
cmd2.ExecuteNonQuery()
cmd3.ExecuteNonQuery()
cmd.ExecuteReader()
'show label to quantity updated
lblNoStock.Visible = True
' lblNoStock.Text = "Updated!"
Finally
conn.Close()
'Response.Redirect("Cart2.aspx")
End Try
Else
'show label to say no more in stock
lblNoStock.Visible = True
lblNoStock.Text = "Cannot reduce quantity: Remove from Cart!"
End If
' else
' lblNoStock.Visible = True
' lblNoStock.Text = "Cannot reduce quantity of Detailing/ Valeting services: Remove from Cart!"
Else
'Outer ELSE
'show label to say cannot change quantity
lblNoStock.Visible = True
lblNoStock.Text = "Quantity cannot be changed for Detailing and Valeting services!"
End If
End Sub
I am also having the same issue with the "+" link button to increase quantity of selected product by 1 in the cart. Reduced code:
Protected Sub lIncrease_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim conn As SqlConnection = New SqlConnection(ConnectionString)
Dim exists As Boolean = False
'Check available in Products table STOCK
Dim cmd As SqlCommand = New SqlCommand
cmd.CommandText = "Select Stock from Products where ProductID = #ProductID"
cmd.Connection = conn
conn.Open()
Dim ProductID As SqlParameter = New SqlParameter("#ProductID", SqlDbType.Int, 4)
ProductID.Value = SCProductID
cmd.Parameters.Add(ProductID)
'check if more than 0 in stock
exists = (CType(cmd.ExecuteScalar, Integer) > 0)
If exists Then
conn.Close()
Dim cmd4 As SqlCommand = New SqlCommand
cmd4.CommandText = "SELECT products.CategoryID FROM products INNER JOIN Cart on products.ProductID = cart.ProductID WHERE cart.productID=#ProductID"
Dim ProductID2 As SqlParameter = New SqlParameter("#ProductID", SqlDbType.Int, 4)
ProductID2.Value = SCProductID
cmd4.Parameters.Add(ProductID2)
cmd4.Connection = conn
conn.Open()
cmd4.ExecuteNonQuery()
Dim reader As SqlDataReader = cmd4.ExecuteReader
Dim CategoryID As Integer
While reader.Read()
CategoryID = CType(reader.Item("CategoryID"), Integer)
End While
'Testing CategoryID value = success
' lblNoStock.Visible = True
'lblNoStock.Text = CategoryID
conn.Close()
'NESTED IF STATEMENT
If CategoryID = "3" Or "4" Then
' UPDATE cart QUANTITY & SUBTOTAL based on CartID
cmd1.CommandText = "UPDATE Cart SET Quantity = Quantity + 1, Subtotal = #Subtotal + #Price WHERE CartID = #CartID"
Dim cmd2 As SqlCommand = New SqlCommand
'UPDATE cart HOURSWORK
cmd2.CommandText = "/"
Dim cmd3 As SqlCommand = New SqlCommand
'UPDATE cart HOURSWORK
cmd3.CommandText = "/"
cmd1.Connection = conn
cmd2.Connection = conn
cmd3.Connection = conn
conn.Open()
//Declared Parameters
Try
cmd1.ExecuteNonQuery()
cmd2.ExecuteNonQuery()
cmd3.ExecuteNonQuery()
cmd.ExecuteReader()
Finally
conn.Close()
Response.Redirect("Cart2.aspx")
End Try
Else
'Nested ELSE
'show label to say cannot change quantity
lblNoStock.Visible = True
lblNoStock.Text = "Quantity cannot be changed for Detailing and Valeting services!"
End If
Else
'show label to say no more in stock
lblNoStock.Visible = True
lblNoStock.Text = "Sorry out of stock!"
End If
End Sub
Two tables:
CART (CartID, UserID, DateCreated, ProductID, ProductName, Size, Price, Quantity, Subtotal, HoursWork)
PRODUCTS (ProductID, Name, SDescription, Price, Size, Images, Thumbnail, Weight, LDescription, Stock, CategoryID, HoursWork)
All working correctly now.
Changed from:
Dim reader As SqlDataReader = cmd4.ExecuteReader
Dim CategoryID As Integer
While reader.Read()
CategoryID = CType(reader.Item("CategoryID"), Integer)
End While
conn.Close()
If CategoryID = "3" Or "4" Then
To:
Dim reader As SqlDataReader = cmd4.ExecuteReader
While reader.Read()
lblTest3.Text = CType(reader.Item("CategoryID"), Integer)
End While
conn.Close()
If lblTest3.Text.Contains("3") Or lblTest3.Text.Contains("4") Then

error when sending email from asp.net contact page

Iam trying to send an email from my contact page but I keep getting an error
I have pasted my code below as well as the error message that is appearing.
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
'
Dim SendPw As New System.Net.Mail.MailMessage
Dim Smtp As New System.Net.Mail.SmtpClient()
SendPw.To.Add(email.Text)
SendPw.From = New System.Net.Mail.MailAddress("shumbasoft#gmail.com")
SendPw.Subject = "Password for you"
SendPw.Priority = Net.Mail.MailPriority.High
SendPw.Body = "This your new password: "
SendPw.IsBodyHtml = False
Smtp.Host = "smtp.gmail.com"
Smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.PickupDirectoryFromIis
Smtp.Send(SendPw)
End Sub
Have you configure IIS ? or make a try with this code, it give good result for me:
Dim msgMail As New MailMessage()
Dim myMessage As New MailMessage()
myMessage.From = New MailAddress("sender's email", "sender`s name and surname")
myMessage.[To].Add("recipient's email")
myMessage.Subject = "Subject"
myMessage.IsBodyHtml = True
myMessage.Body = "Message Body"
Dim mySmtpClient As New SmtpClient()
Dim myCredential As New System.Net.NetworkCredential("email", "password")
mySmtpClient.Host = "your smtp host address"
mySmtpClient.UseDefaultCredentials = False
mySmtpClient.Credentials = myCredential
mySmtpClient.ServicePoint.MaxIdleTime = 1
mySmtpClient.Send(myMessage)
myMessage.Dispose()
you need to import Imports system.net.mail
this did the trick for me!! from the localhost to gmail
Dim Body As String = "From: " + fname.Text + " " + lname.Text + Environment.NewLine + "Email: " + email.Text + Environment.NewLine + Environment.NewLine + "Message" + Environment.NewLine + txtComment.Text
Dim xx As New System.Net.Mail.SmtpClient
xx.EnableSsl = True
xx.Host = "smtp.gmail.com"
Dim cred As New System.Net.NetworkCredential("example#gmail.com", "examplepassword")
xx.Credentials = cred
xx.Send(email.Text, "sendexample#gmail.com ", subject.Text, Body)
ClearFields()
lblEmail.ForeColor = Drawing.Color.Green
lblEmail.Text = "message sent"
lblEmail.Visible = True

The thread was interrupted

I am using this code to update database with new values. But it return message The thread was interrupted. What does it mean? What is wrong with my code?
Dim connStr As String = System.Configuration.ConfigurationManager.ConnectionStrings("DeskriptivaConnectionString").ConnectionString.ToString()
Dim txtName As Object = DirectCast(FormView1.FindControl("txtName"), TextBox)
Dim txtLastName As Object = DirectCast(FormView1.FindControl("txtLastName"), TextBox)
Dim txtInfo As Object = DirectCast(FormView1.FindControl("txtInfo"), TextBox)
Dim txtCity As Object = DirectCast(FormView1.FindControl("txtCity"), TextBox)
Dim txtPrize As TextBox = DirectCast(FormView1.FindControl("txtPrize"), TextBox)
Dim txtPhone As TextBox = DirectCast(FormView1.FindControl("txtPhone"), TextBox)
Dim txtMail As TextBox = DirectCast(FormView1.FindControl("txtMail"), TextBox)
Try
Using conn As New SqlConnection(connStr)
Dim cmd As SqlCommand = conn.CreateCommand()
cmd.CommandText = "UPDATE Profiles SET #Name = Name, #LastName = LastName, #Info = Info, #City = City, #Prize = Prize, #Phone = Phone, #Mail = Mail WHERE (UserName = #UserName)"
cmd.Parameters.Add("#Name", System.Data.SqlDbType.NVarChar).Value = txtName.Text
cmd.Parameters.Add("#LastName", System.Data.SqlDbType.NVarChar).Value = txtLastName.Text
cmd.Parameters.Add("#Info", System.Data.SqlDbType.NText).Value = MakeLink(HtmlRemoval.StripTagsCharArray(txtInfo.Text))
cmd.Parameters.Add("#City", System.Data.SqlDbType.NVarChar).Value = txtCity.Text
cmd.Parameters.Add("#Prize", System.Data.SqlDbType.NVarChar).Value = txtPrize.Text
cmd.Parameters.Add("#Phone", System.Data.SqlDbType.NVarChar).Value = txtPhone.Text
cmd.Parameters.Add("#Mail", System.Data.SqlDbType.NVarChar).Value = txtMail.Text
cmd.Parameters.Add("#UserName", System.Data.SqlDbType.NVarChar).Value = Context.User.Identity.Name
conn.Open()
cmd.ExecuteNonQuery()
conn.Close()
Response.Redirect(ResolveClientUrl("~/Profil/"))
End Using
Catch ex As Exception
MsgBox(ex.Message)
End Try
Use Response.Redirect(ResolveClientUrl("~/Profil/"), false) with Context.ApplicationInstance.CompleteRequest(); instead of Response.Redirect(ResolveClientUrl("~/Profil/"))
check Correct use of System.Web.HttpResponse.Redirect blog post for more information
and also your sql parameters # symbol is in wrong place. change as below
UPDATE Profiles SET
Name = #Name, LastName
= #LastName, Info =
#Info, City = #City,
Prize = #Prize, Phone
= #Phone, Mail = #Mail
WHERE (UserName =
#UserName)

MVC Filtering A-Z

I have made the MVC Music Store from the tutorials and am editing it and adding new features, recently I made the browse store page have links from A-Z with an All button at the end.
How can I bring up a message that says "There are no artists beginning with the letter A, B, C " or whatever letter has been clicked with no artists.
Here is my code from my Store Index:
#model IEnumerable<MVCMusicStore.Models.Artist>
#{
ViewBag.Title = "Store";
}
<h3>Browse Artists</h3>
#Html.ActionLink("A", "Index", new { letter = "A" })
#Html.ActionLink("B", "Index", new { letter = "B" })
#Html.ActionLink("C", "Index", new { letter = "C" })
#Html.ActionLink("D", "Index", new { letter = "D" })
#Html.ActionLink("E", "Index", new { letter = "E" })
#Html.ActionLink("F", "Index", new { letter = "F" })
#Html.ActionLink("G", "Index", new { letter = "G" })
#Html.ActionLink("H", "Index", new { letter = "H" })
#Html.ActionLink("I", "Index", new { letter = "I" })
#Html.ActionLink("J", "Index", new { letter = "J" })
#Html.ActionLink("K", "Index", new { letter = "K" })
#Html.ActionLink("L", "Index", new { letter = "L" })
#Html.ActionLink("M", "Index", new { letter = "M" })
#Html.ActionLink("N", "Index", new { letter = "N" })
#Html.ActionLink("O", "Index", new { letter = "O" })
#Html.ActionLink("P", "Index", new { letter = "P" })
#Html.ActionLink("Q", "Index", new { letter = "Q" })
#Html.ActionLink("R", "Index", new { letter = "R" })
#Html.ActionLink("S", "Index", new { letter = "S" })
#Html.ActionLink("T", "Index", new { letter = "T" })
#Html.ActionLink("U", "Index", new { letter = "U" })
#Html.ActionLink("V", "Index", new { letter = "V" })
#Html.ActionLink("W", "Index", new { letter = "W" })
#Html.ActionLink("X", "Index", new { letter = "X" })
#Html.ActionLink("Y", "Index", new { letter = "Y" })
#Html.ActionLink("Z", "Index", new { letter = "Z" })
#Html.ActionLink("All", "Index", new { letter = "all" })
<ul>
#foreach (var artist in Model)
{
<li>#Html.ActionLink(artist.Name,
"Browse", new { id = artist.ArtistId })</li>
}
</ul>
This is the code from my Controller:
public ActionResult Index(string letter = "")
{
IEnumerable<Artist> artist;
if (letter == "all")
{
artist = storeDB.Artists.OrderBy(x =>x.Name).ToList();
}
else if (letter != "")
{
artist = storeDB.Artists.Where(a => a.Name.StartsWith(letter)).OrderBy(x => x.Name).ToList();
}
else
{
artist = new List<Artist>();
}
To make your view neater you could use:
#for (int y = 0; y < 27; y++) {
char filter = Convert.ToChar(65 + y);
string letter = filter.toString();
if(y == 27){
letter = "All";
}
#Html.ActionLink(letter, "Index", new { letter = letter });
}
This will save all those action links
#if(Model.Any())
{
foreach (var artist in Model)
{
<li>#Html.ActionLink(artist.Name,
"Browse", new { id = artist.ArtistId })</li>
}
}
else
{
<span>There are no artists</span>
}

How to remove the link if value is 0 using asp.net mvc

awesome worked fine for me.. due to security I am editing my code..
thanks
Update:
Replace
<%=Html.ActionLink(e.ExceptionTypeName, "VirtualScrollingDataRequested", Model.exceptionCategory.GetControllerName(), new { C_EXCPT_TYPE = e.ExceptionTypeID, GUI_SPEC_STAT_DSPL = 2, C_EXCPT_CATG = Model.exceptionCategory.Id, #ASSET_CLASS = string.Empty, #INST_MNEM = string.Empty, #_lock = "ALL" }, new { #title = e.BuildGridTitle(2, e.ExceptionTypeName) })%>
with
<%=e.workedexceptions == 0 ? e.ExceptionTypeName : Html.ActionLink(e.ExceptionTypeName, "VirtualScrollingDataRequested", Model.exceptionCategory.GetControllerName(), new { C_EXCPT_TYPE = e.ExceptionTypeID, GUI_SPEC_STAT_DSPL = 2, C_EXCPT_CATG = Model.exceptionCategory.Id, #ASSET_CLASS = string.Empty, #INST_MNEM = string.Empty, #_lock = "ALL" }, new { #title = e.BuildGridTitle(2, e.ExceptionTypeName) }) %>

Resources