Unable to cast object of type 'ItemStore.Item' to type 'System.Collections.IEnumerable' - asp.net-mvc

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

Related

How to Fill Drop Down List using Model in 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.

convert arraylist into IList in vb.net

I am getting an arraylist in view from controller. In view when i try to display that array error occur "Unable to cast object of type 'System.Collections.ArrayList' to type 'System.Collections.Generic.IList`1". my code is as below
Dim c As IList(Of myclass) = CType(Model, IList(Of myclass)) (arraylist from controller)
In Model there is an arraylist. I don't know how to cast this arraylist into IList. Please help. Thanks
Dim iplist = (From d In db.mytable Select d).ToList
Dim c2 As ArrayList
For i As integer = 0 to iplist.Count - 1
Dim ip = iplist(i).ip
Dim c as countrylist
c.country = country
c.city = city
Next
Class cou1ntrylist
Public country As String
Public city As New ArrayList
End Class

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

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.

Combining extension methods

I'm trying to write 2 extension methods to handle Enum types. One to use the description attribute to give some better explanation to the enum options and a second method to list the enum options and their description to use in a selectlist or some kind of collection.
You can read my code up to now here:
<Extension()> _
Public Function ToDescriptionString(ByVal en As System.Enum) As String
Dim type As Type = en.GetType
Dim entries() As String = en.ToString().Split(","c)
Dim description(entries.Length) As String
For i = 0 To entries.Length - 1
Dim fieldInfo = type.GetField(entries(i).Trim())
Dim attributes() = DirectCast(fieldInfo.GetCustomAttributes(GetType(DescriptionAttribute), False), DescriptionAttribute())
description(i) = If(attributes.Length > 0, attributes(0).Description, entries(i).Trim())
Next
Return String.Join(", ", description)
End Function
<Extension()> _
Public Function ToListFirstTry(ByVal en As System.Enum) As IEnumerable
Dim type As Type = en.GetType
Dim items = From item In System.Enum.GetValues(type) _
Select New With {.Value = item, .Text = item.ToDescriptionString}
Return items
End Function
<Extension()> _
Public Function ToListSecondTry(ByVal en As System.Enum) As IEnumerable
Dim list As New Dictionary(Of Integer, String)
Dim enumValues As Array = System.Enum.GetValues(en.GetType)
For Each value In enumValues
list.Add(value, value.ToDescriptionString)
Next
Return list
End Function
So my problem is both extension methods don't work that well together. The methods that converts the enum options to an ienumerable can't use the extension method to get the description.
I found all kind of examples to do one of both but never in combination with each other. What am I doing wrong? I still new to these new .NET 3.5 stuff.
The problem is that Enum.GetValues just returns a weakly typed Array.
Try this:
Public Function ToListFirstTry(ByVal en As System.Enum) As IEnumerable
Dim type As Type = en.GetType
Dim items = From item In System.Enum.GetValues(type).Cast(Of Enum)() _
Select New With {.Value = item, .Text = item.ToDescriptionString}
Return items
End Function
(It looks like explicitly typed range variables in VB queries don't mean the same thing as in C#.)

Resources