Default Value For Dropdown List - vb.net

I need to set a default value for the DropDown list as follows:
#Html.DropDownList("BillId", "")
The user doesn't necessarily need to select something but the list throws an error
The ViewData item that has the key 'BillId' is of type 'System.Int32' but must be of type 'IEnumerable<SelectListItem>'
if a value is not selected and the box is left on it's default blank state.
My controllers as follows:
Function Create(id As Integer) As ViewResult
ViewBag.id = id
Dim job As Job = New Job
job.CustomerId = id
job.JobAmount = 0
job.JobDate = Date.Now()
job.JobStatus = "Active"
Dim BillList = New List(Of Bill)()
Dim BillQuery = From s In db.Bills
Select s
BillList.AddRange(BillQuery)
ViewBag.BillId = New SelectList(BillList, "BillId", "BillDate")
Return View(job)
End Function
'
' POST: /Job/Create
<HttpPost()>
Function Create(job As Job) As ActionResult
If ModelState.IsValid Then
db.Jobs.Add(job)
db.SaveChanges()
Dim customer As Customer = db.Customers.Find(job.CustomerId)
Dim customerNumber As String = customer.CustCellphone.ToString()
Dim messageSender As SendMessage = New SendMessage
Dim smsMessage As String = "LAUNDRY: Job Number " & job.JobId & " has been booked in. You will be notified when individual services within it are ready for collection."
messageSender.SendMessage(smsMessage, customerNumber)
Dim url As String = "/RequestedService/AddService/" + job.JobId.ToString()
Return Redirect(url)
End If
Return View(job)
End Function

If your model Job doesn't have the property of BillId than in the view the dropdown markup should be
#Html.DropDownList("Job_BillId", ViewBag.BillId)
And the model Job contains the property BillId than create the ViewBag with some different name and use them accordingly in view markup for example:
Create a ViewBag with different name instead of BillId in controller
ViewBag.BillIdList = New SelectList(BillList, "BillId", "BillDate")
And in view use this as below
#Html.DropDownListFor(model => model.BillId, ViewBag.BillIdList)
Hope this will help you.

Related

(VB.NET) Find all duplicates in a list of objects based on multiple properties

I have a list of CommissionStatement objects which i created. I need to create a new list which only holds the duplicates found in this list based on 3 properties: Firm; Provider; and Total (ie each of these 3 have to be the same in 2 or more objects for it to be recognized as a duplicate)
Object is a simple object of strings at the moment.
Private Class CommissionStatement
Property Provider As String
Property Firm As String
Property Source As String
Property Media As String
Property Total As String
Property Received As String
End Class
I have a list of all CommissionStatments as follows:
Dim fileLocation As String = importText.Text
Dim csvText As String = My.Computer.FileSystem.ReadAllText(fileLocation).Replace(", ", " ")
Dim providerString As String = ""
Dim allStatements = New List(Of CommissionStatement)
Dim countIndex As Integer = 0, maxIndex As Integer = csvText.Split(vbLf).Length
For Each line As String In csvText.Split(vbLf)
'' Remove the top row
countIndex += 1
If countIndex = 1 Then
Continue For
End If
statementProgress.Value = ((countIndex / maxIndex) * 100)
'' Build the New commissionStatement object and add it to the allStatements list
If Not line = "" Then
Dim commissionStatement = New CommissionStatement
With commissionStatement
.Provider = line.Split(",")(0)
.Firm = line.Split(",")(1)
.Source = line.Split(",")(2)
.Media = line.Split(",")(3)
.Total = line.Split(",")(4)
End With
providerString &= commissionStatement.Provider & ","
allStatements.Add(commissionStatement)
End If
Next
First post on StackOverflow so sorry if its not very clear! The duplicate list needs to also be a list of CommissionStatements which contain the duplicates from the allStatements list based on Firm Provider and Total
Your best bet is to use a lambda expression. The function below should do what you ask.
Private Function GetDuplicateCommisionStatements(tempStatement As CommissionStatement) As List(Of CommissionStatement)
Return allStatements.FindAll(Function(x) x.Firm = tempStatement.Firm And x.Provider = tempStatement.Provider And x.Total = tempStatement.Total)
End Function
And use it like this..
duplicatelist = GetDuplicateCommisionStatements(testCommisionStatement)
using your own object names of course.
Incidentally, you could shorten the sub using the With statement like below
Private Function GetDuplicateCommisionStatements(tempStatement As CommissionStatement) As List(Of CommissionStatement)
With tempStatement
Return allStatements.FindAll(Function(x) x.Firm = .Firm And x.Provider = .Provider And x.Total = .Total)
End With
End Function

MVC pass two objects to view

I am just struggling with passing two objects to my view and then show data out of it. On purpose to send two diffrent objects to a view i maked separated class for it which would contain my two class object to be pased as follows:
Public Class CustomModelProjetsTransports
Public Projects As IEnumerable(Of woitgroup_transport.tbProjekt)
Public Transports As IEnumerable(Of woitgroup_transport.tbTransport)
End Class
Now in my controlled i am pasing by it to a view (i checked and the data is there:
Function Index() As ActionResult
If Not IsNothing(Session("LogedUserId")) Then
Dim userId As Integer = Session("LogedUserId")
Dim projectsAndTransportsLists As New CustomModelProjetsTransports
Dim ProjectsPerUser As New List(Of tbProjekt)
ProjectsPerUser = db.Database.SqlQuery(Of tbProjekt)("SELECT * FROM [mydb].[dbo].[tbProjekt] where Id IN (SELECT DISTINCT ProjectId FROM [mydb].[dbo].[tbUserProject] WHERE UserId = " & Session("LogedUserId") & ")").ToList
Dim transportsPerUser As New List(Of tbTransport)
transportsPerUser = db.Database.SqlQuery(Of tbTransport)("SELECT * FROM [mydb].[dbo].[tbTransport] where ProjectId IN (SELECT DISTINCT ProjectId FROM [mydb].[dbo].[tbUserProject] WHERE UserId = " & Session("LogedUserId") & ")").ToList
projectsAndTransportsLists.Projects = ProjectsPerUser
projectsAndTransportsLists.Transports = transportsPerUser
Return View(projectsAndTransportsLists)
Else
Return RedirectToAction("Index", "Login")
End If
End Function
problem is here within View:
this is on top:
#ModelType IEnumerable(Of woitgroup_transport.CustomModelProjetsTransports)
<tbody>
#For Each item In Model(1).Transports.ToList
Dim currentItem = item
#<tr>
...
when i am executing my application its filling out correctly here:
Return View(projectsAndTransportsLists)
but then i am reciving an error when view wants to be shown as follows:
The model item passed into the dictionary is of type 'woitgroup_transport.CustomModelProjetsTransports', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable`1[woitgroup_transport.CustomModelProjetsTransports]'.
Additional question:
Kepping on mind i have Projects list within my view how to correctly fill in dropdown (the best using bootstrap styles). I am trying like that but still something wrong...
#Html.DropDownListFor(Function(m) m.Projects.., DirectCast(Model.Projects, SelectList), New With { _
.class = "form-control" _
})
its also saying that Function(m) m.Projects.Name
that Name is not exist - i see only generic list on intelisense like Function(m) m.Projects.ToList ...
The error message is quite clear about the problem. You are passing a CustomModelProjetsTransports to the view. But the view expects a IEnumerable(Of CustomModelProjetsTransports). Remove the IEnumerable and you should be fine.

WCF EF return as list

Hi I got the error when return EF as the list. Here are my codes.
WCF
Public Function GetMerchantList() As List(Of Merchant) Implements IMerchant.GetMerchantList
Dim ws As New aMerchantService.MerchantServiceClient
Dim General As New General
Dim kWSUrl As String = ""
Dim endpointAddress = ws.Endpoint.Address
Dim newEndpointAddress As New EndpointAddressBuilder(endpointAddress)
kWSUrl = General.ConvertWsURL("App")
newEndpointAddress.Uri = New Uri(kWSUrl & "MerchantService.svc")
ws = New aMerchantService.MerchantServiceClient("BasicHttpBinding_IMerchantService", newEndpointAddress.ToEndpointAddress())
Dim Data = ws.GetMerchantList()
Return Data
End Function
Merchant Class
Public Function GetMerchantList() As List(Of Merchant)
Dim Db As New TTMSEntities
Dim Data = (From p In Db.TT_MERCHANT Join r In Db.TT_BRANCH_SETTING On _
p.MERCHANT_BRANCH_INTERNAL_NUM Equals r.INTERNAL_NUM _
Select New Merchant With {.MerchantID = p.MERCHANT_ID,
.MerchantName = p.DESCRIPTION,
.BranchID = r.INTERNAL_NUM,
.BranchName = r.BRANCH_DESC})
If Data IsNot Nothing Then
Return Data.ToList
Else
Return Nothing
End If
End Function
The error is Error Value of type '1-dimensional array of
TTMS.App.WebSites.Data.Merchant' cannot be converted to
'System.Collections.Generic.List(Of TTMS.Web.WebSites.WCF.Merchant)'.
Please help. Thanks
It looks like you're using a service reference. By default, WCF will serialize generic lists as arrays. To override this behavior, when you go to add the service reference, click on the Advanced button at the bottom left corner. This will bring up the Service Reference Settings. Select System.Generics.List for the collection type (the default is System.Array):

Function to populate list not working

I am trying to get the following to work
Function AddService(id As Integer) As ViewResult
Dim serv As RequestedService = New RequestedService
serv.JobId = id
Dim ServiceList = New List(Of RequestedService)()
Dim ServiceQuery = From s In db.Services
Select s
ServiceList.AddRange(ServiceQuery)
ViewBag.ServiceId = New SelectList(ServiceList, s.IDServices, s.ServiceName)
Return View(serv)
End Function
But
ViewBag.ServiceId = New SelectList(ServiceList, s.IDServices, s.ServiceName)
Gives me the following error: 's' is not declared. It may be inaccessible due to its protection level.
I cannot work out how to correct this. Essentially I need to populate the SelectList with both an id and string and pass it to the view?
Assuming that the RequestedService model has properties called IDServices and ServiceName you could use the following:
ViewBag.ServiceId = New SelectList(ServiceList, "IDServices", "ServiceName")
But you really don't need this intermediary list:
Function AddService(id As Integer) As ViewResult
Dim serv As RequestedService = New RequestedService
serv.JobId = id
ViewBag.ServiceId = New SelectList(db.Services, "IDServices", "ServiceName")
Return View(serv)
End Function
And you really, really, really don't need to use ViewBag, but use view models instead.
Function AddService(id As Integer) As ViewResult
Dim model = New RequestedServiceViewModel
model.JobId = id
model.Services = New SelectList(db.Services, "IDServices", "ServiceName")
Return View(model)
End Function
and now your view is strongly typed to the view model:
#ModelType RequestedServiceViewModel
#Html.DropDownListFor(Function(x) x.ServiceId, Model.Services)

How do I access the data filters in this MVC3 VB application BEFORE loading the data?

I have a few filters for table data represented by dropdowns, but the table data is really huge and the process hangs for a few minutes until the complete table is rendered; only then is the table presented and I can use those filters.
I want to be able to access the filters before presenting the data; I don't want to wait for the table to load. This could be done by separating the filters into another view/controller, but I want to handle inside the index() method.
I tried to delete the part where the process checks if filters are set, but then than it will work if I set all filters only.
Relevant code:
Function Index(SelectedTimeType As System.Nullable(Of Integer), SelectedTimeStatus As System.Nullable(Of Integer), SelectedProject As System.Nullable(Of Integer), SelectedTask As System.Nullable(Of Integer)) As ActionResult
Dim tipovi = unitOfWork.TimeTypeRepository.Get(orderBy:=Function(q) q.OrderBy(Function(d) d.Opis))
ViewBag.SelectedTimeType = New SelectList(tipovi, "TimeTypeID", "Opis", SelectedTimeType)
Dim statusi = unitOfWork.TimeStatusRepository.Get(orderBy:=Function(q) q.OrderBy(Function(d) d.Opis))
ViewBag.SelectedTimeStatus = New SelectList(statusi, "TimeStatusID", "Opis", SelectedTimeStatus)
Dim projekti = unitOfWork.ProjectRepository.Get(orderBy:=Function(q) q.OrderBy(Function(d) d.Opis))
ViewBag.SelectedProject = New SelectList(projekti, "ProjekatID", "Opis", SelectedProject)
Dim taskovi = unitOfWork.TaskRepository.Get(orderBy:=Function(q) q.OrderBy(Function(d) d.Opis))
ViewBag.SelectedTask = New SelectList(taskovi, "TaskID", "Opis", SelectedTask)
Dim timeTypeID As Integer = SelectedTimeType.GetValueOrDefault()
Dim timeStatusID As Integer = SelectedTimeStatus.GetValueOrDefault()
Dim projekatID As Integer = SelectedProject.GetValueOrDefault()
Dim taskID As Integer = SelectedTask.GetValueOrDefault()
Return View(unitOfWork.TimeTrackingRepository.Get(
filter:=Function(d) Not (SelectedTimeType.HasValue And SelectedTimeStatus.HasValue And SelectedProject.HasValue And SelectedTask.HasValue) OrElse (d.TimeTypeID = timeTypeID And d.TimeStatusID = timeStatusID And d.ProjectID = projekatID And d.TaskID = taskID),
orderBy:=Function(q) q.OrderBy(Function(d) d.TimeTrackingID)))
End Function