I can’t find a good blog post that shows how to bind a model to a view without the "ViewData" magic lines (using a strongly typed view is the approach I'm trying to do)
Does anyone know what I need to change below to link this directly to my model?
View
<%@ Page Language="VB" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage(Of IEnumerable (Of MvcApplication1.Category))" %>
<asp:Content ID="aboutContent" ContentPlaceHolderID="MainContent" runat="server">
<%=Html.DropDownList("CategoryList")%>
</asp:Content>
controller
Function Index() As ActionResult
Dim list As New List(Of Category)
list.Add(New Category With {.CategoryID = 1, .CategoryName = "Test1"})
list.Add(New Category With {.CategoryID = 2, .CategoryName = "Test2"})
Return View()
End Function
EDIT
The final solution in VB is shown below, thanks for the great answer!
controller
Function Index() As ActionResult
Dim id As Integer = 1
Dim ProductObject As Product = mProductService.GetProductById(id)
Return View(ProductObject)
End Function
View
<%=Html.DropDownList("Category", New SelectList(Model.Categories, "CategoryID", "CategoryName"))%>
Product class (without IEnumeralbe property for categories)
Public Class Product
Public Sub New()
End Sub
Private mProductID As Integer
Public Property ProductID() As Integer
Get
Return mProductID
End Get
Set(ByVal value As Integer)
mProductID = value
End Set
End Property
ReadOnly Property Categories() As IEnumerable(Of Category)
Get
Dim list As New List(Of Category)
list.Add(New Category With {.CategoryID = 1, .CategoryName = "Test1"})
list.Add(New Category With {.CategoryID = 2, .CategoryName = "Test2"})
Return list
End Get
End Property
End Class
source
share