How to Fill Drop Down List using Model in MVC - asp.net-mvc

Function GetStateName() As List(Of SelectListItem)
Dim ListRoomMaster As List(Of MiscMaster) = New List(Of MiscMaster)
Dim rm As New MiscMaster
Using conn As New SqlConnection(connectionString)
Dim sSql = "Select * From dropdown"
Dim cmd As SqlCommand = New SqlCommand(sSql, conn)
conn.Open()
Dim rst As SqlDataReader = cmd.ExecuteReader
Do While rst.Read
rm.m_ddlId = rst!id
rm.ddlValue = rst!name
ListRoomMaster.Add(rm)
Loop
End Using
Dim Listxyz = (
From p In Enumerable.Range(0, 20)
Select New SelectListItem With {.Text = p.ToString(), .Value = p.ToString()})
Return Listxyz.ToList()
End Function
This is the code for GetStateName() Which I am calling from controller Before Viewing This Displays The Drop Down List With 0 to 19 numbers I know I have Miss Something But Don't Know Where to change as most of code are for Linq
This Is Controller Code
Function Index() As ActionResult
objMisc.StateValue = objMisc.GetStateName()
'objMisc.StateValue = obj
Return View(objMisc)
End Function
What I Exactly Want Is Fetching data from DataBase using query
DataBase Have field like follow
id | Value
1 | xyz
2 | abx
3 | kvd
I want to populate drop down List As xyz,abx,kvd
And when abx is selected I want to store 2 in database

If you are working with MVC then you can also get the Data directly in the Razor View from your Model. Because you are doing a SQL Query manually which isnt the puropse of MVC.
Your should return the Model and then you can simply do this:
#Html.DropDownListFor(m => m.column, Model.dropdown)

Let's make a couple of models:
public NameCode(string name)
{
Name = name;
Code = name;
}
public NameCodeCollection(IEnumerable<NameCodeItem> list) : base(list)
{
}
In razor:
#Html.DropDownListFor(m => m.modelid, new SelectList(Model.modeltext, "Name", "Code"))
Use the namecodecollection to feed your dropdown list & read from it.

Related

Getting a value from one table to pull up values from another table

I am trying to lookup an employeeid from one table based on the windows login name, and use this employeeid to get values from another table to add them up. So, for Bill, the employeeid is 1 in tblEmployees. I sum all noofhours in tblTimeAvailable where employeeid equals 1 and display this on my webpage. It's not working. I can't figure out how to search the second table by the employeeid found in the first table. (I'm rewriting code because of sql injection.)
Dim windowsLoginName As System.String = HttpContext.Current.User.Identity.Name 'System.Security.Principal.WindowsIdentity.GetCurrent().Name
Dim split As String() = Nothing
Dim vname As String
'Get network login name (name only)
split = windowsLoginName.Split("\".ToCharArray)
vname = split(1)
Dim Connection As String = "Data Source=WillSQL\ict2;Initial Catalog=TimeSQL;Integrated Security=SSPI"
Using con As New SqlConnection(Connection)
Dim sqlemp As String = "SELECT EmployeeID FROM tblEmployees where login = #loginname"
Dim command As New SqlCommand(sqlemp, con)
con.Open()
rve = cmde.Parameters.Add(New SqlParameter With {.ParameterName = "#loginname", .SqlDbType = SqlDbType.NVarChar, .Value = vname})
End Using
When I look at value of rve, it's giving me #loginname and not the employeeid. FYI - there will always be only one row in tblEmployees because each Windows login name is unique.
'Get Sick Time
Using con As New SqlConnection(Connection)
Dim sqls1 As String = "Select SUM(NoofHours) as Total from tblTimeAvailable where workcode = 1 and EmployeeID = #employeeid"
Dim command As New SqlCommand(sqls1, con)
con.Open()
rvsa = cmde.Parameters.Add(New SqlParameter With {.ParameterName = "#employeeid", .SqlDbType = SqlDbType.NVarChar, .Value = rve})
End Using
' If the sum equals 0, show 0 on webpage. If another value, show value.
If IsDBNull(rvsa) Then
rvsa = 0
TextBoxsa.Text = 0
Else
TextBoxsa.Text = rvsa.ToString
End If
I appreciate any help you can give me!
You are never executing the command. After setting the values of the various parameters, you need to then call one of the execute methods on the SqlCommand object. In this case, since you are just reading a single value from a single row, you can simply use the ExecuteScalar method:
rve = command.ExecuteScalar()

Unable to cast object of type 'ItemStore.Item' to type 'System.Collections.IEnumerable'

Having a problem displaying the list of items in the view. Can't convert it from a ItemStore.Item to IEnumerable, I've also added ' #Method List(Of ItemStore.Item) ' to list.vbhtml and it can't display The item passed into the dictionary becuase is of type 'Item Store.Item', but this dictionary requires a model item of type 'System.Collections.Generic.List`1[Item Store.Item]'.
****CatalogueController**********
Function About() As ActionResult
Return View()
End Function
Function Index() As String
Return "Index"
End Function
Function List(search As String) As ActionResult
Dim model As New SQLItemModel
Dim items = model.SelectById(search)
Return View(items)
End Function
******List.vbhtml***********
The search text is #ViewBag.Message
#For Each item In Model
#item.ID
*********SQLItemModel.vb***********
Private connectionString As String = My.Settings.sqlconnection
Public Function SelectAll() As ICollection(Of Item)
Dim items As New List(Of Item)
Using connection As New SqlConnection(connectionString)
connection.Open()
Dim cmd As New SqlCommand("select * from item", connection)
Dim reader As SqlDataReader = cmd.ExecuteReader()
While reader.Read()
items.Add(GetItem(reader))
End While
End Using
Return items
End Function
Public Function SelectById(ItemID As Integer) As Item
Dim item As Item = Nothing
Using connection As New SqlConnection(connectionString)
connection.Open()
Dim cmd As New SqlCommand()
cmd.CommandText = "select * from Tbl_Items where ID = #ID"
cmd.Connection = connection
cmd.Parameters.Add(New SqlParameter("ID", ItemID))
Dim reader As IDataReader = cmd.ExecuteReader()
If reader.Read() Then
Item = GetItem(reader)
End If
End Using
Return Item
End Function
Private Function GetItem(reader As SqlDataReader) As Item
Dim ID = reader("ID")
Dim ProductCode = reader("ProductCode")
Dim Brand = reader("Brand")
Dim Description = reader("Description")
Dim Colour = reader("Colour")
Dim Finish = reader("Finish")
Dim Type = reader("Type")
Dim Size = reader("Size")
Dim Unit = reader("Unit")
Return New Item(ID, ProductCode, Brand, Description, Colour, Finish, Type, Size, Unit)
End Function
SelectById just returns a single Item (while SelectAll returns a collection of Items), but your List view expects a collection.
An easy fix would be to just wrap the single item in an array:
Function List(search As String) As ActionResult
Dim model As New SQLItemModel
Dim items = model.SelectById(search)
Return View({items})
End Function

Drop-down list not populating other controls

I am a complete newb to webapps but here goes.
I have web form with a drop-down list that populates a list of holiday resorts from a database procedure. That bit works fine. When I select an item from the list I need to populate a listbox with hotels specific to that resort.
This bit I am having trouble with, the list does populate if I click off the drop-down list onto a calendar control on the form.
Question: how do I get it to populate the list after I clcik on the value from the drop-down list?
Thanks
Here is the code by the way:
Private Sub Page_Init(sender As Object, e As System.EventArgs) Handles Me.Init
Me.Calendar1.SelectedDate = Now()
Me.DropDownList1.Items.Clear()
Dim connStr As String = Web.Configuration.WebConfigurationManager.ConnectionStrings("ITC").ConnectionString
Dim conn As New SqlClient.SqlConnection(connStr)
conn.Open()
Dim sqlProducts As String = "<<sql_string>>"
Dim da As New SqlDataAdapter(sqlProducts, conn)
Dim ds As New DataSet()
da.Fill(ds, "Products")
DropDownList1.DataTextField = "Rcode"
DropDownList1.DataValueField = "Rcode"
DropDownList1.DataSource = ds.Tables("Products")
DropDownList1.DataBind()
ds.Dispose()
da.Dispose()
conn.Close()
End Sub
Protected Sub DropDownList1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DropDownList1.SelectedIndexChanged
Me.ListBox1.Items.Clear()
Me.ListBox2.Items.Clear()
Dim connStr As String = WebConfigurationManager.ConnectionStrings("ITC").ConnectionString
Dim conn As New SqlConnection(connStr)
conn.Open()
Dim sqlProducts As String = "sql_string '" & Me.DropDownList1.Text & "'"
Dim da As New SqlDataAdapter(sqlProducts, conn)
Dim ds As New DataSet()
da.Fill(ds, "Products")
ListBox1.DataTextField = "accommDescription"
ListBox1.DataValueField = "accommCode"
ListBox1.DataSource = ds.Tables("Products")
ListBox1.DataBind()
ds.Dispose()
da.Dispose()
conn.Close()
ListBox1.Focus()
End Sub

Error when trying to use context.entity.include()

I am trying to filter records and return them to put them in a list. My variable "companyId" equals 1. When I run, I get an error. What can I do to fix? Thank you.
The error points to this line:
Dim blogs = db.Blogs.Include(Function(b) b.CompanyId = companyId)
The error:
The Include path expression must refer to a navigation property defined on the type. Use dotted paths for reference navigation properties and the Select operator for collection navigation properties.
Parameter name: path
The whole code:
'
' GET: /ViewBlogs/
Function ViewBlogs() As ViewResult
'Dim blogs = db.Blogs.Include(Function(b) b.Company)
Dim db1 As UserProfileDbContext = New UserProfileDbContext
Dim user = Membership.GetUser()
Dim key As Guid = user.ProviderUserKey
Dim userProfile = db1.UserProfiles.Where(Function(p) p.UserId = key).Single
Dim companyId = userProfile.CompanyId
If (userProfile.IsCompanyOwner) Then
Dim blogs = db.Blogs.Include(Function(b) b.CompanyId = companyId)
Return View(blogs.ToList())
Else
Return View("Home")
End If
End Function
Yes, the solution for me was as simple as this:
Dim blogs = db.Blogs.Where(Function(b) b.CompanyId = companyId)

Sorting or Ordering values returned in a EF query MVC 3 vb.net app

I am using a where comparer in the below snippet from my function.. I need to order or sort the returned items by one of the columns... I tried using .OrderBy(function(f) f.regDate) but that dont work at all...
The part of the function in question looks like this:
Function ClassFiller() As ActionResult
Dim _courses As List(Of cours) = db.courses.ToList
Dim _registrants As List(Of reg_info) = db.reg_info.ToList
Dim _classSpec As List(Of classrm) = db.classrms.ToList
Dim _CurrRegistrants As List(Of reg_classes) = db.reg_classes.ToList
For Each Course In _courses.Where(Function(a) a.course_day = "Tuesday")
Dim _CurrCourse As cours = Course
Dim _classRoom As classrm = db.classrms.Where(Function(b) b.Course_ID = _CurrCourse.course_ref).FirstOrDefault()
Dim _classmax As Integer = _classRoom.ClassMax - 1
For Each reg In _registrants.Where(Function(d) d.tues_class1 = _CurrCourse.course_ref).OrderBy(Function(f) f.reg_date)
Dim _ClassCount As Integer = db.reg_classes.Where(Function(c) c.tues_class = _CurrCourse.course_ref).Count
I need to have the _registrants ordered or sorted by a value that is in the db.reg_info under the reg_date column... Any ideas??
Where _registrant is declared at I should have used the following instead:
Dim _registrants As List(Of reg_info) = db.reg_info.OrderBy(Function(t) t.reg_date).ToList
then it will already be ordered.. So the orderby is not needed in the For Each reg In _Registrants.

Resources