I have a dropdown on my homepage that I need to bind to a data source when the page loads. I have a basic controller for the page:
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
}
I'd like to do something like this on the view page:
<select id="ddlCities">
<% foreach (var item in ViewData.Model.Cities) { %>
<option value='<%= item.CityID %>'><%= item.CityName %></option>
<% } %>
</select>
So do I need to modify my Index() function to return a View Model? I'm coming from Web Forms and a little confused about how this works.
Steven,
You can do it even simpler than that. Just use the html helper:
<%=Html.DropDownList("ddlCities", ViewData["Cities"])%>
this 'should' work for you, as long as your model has an ienumerable list called Cities.
of course, your 'best' course of action would be to have a strongly typed model that was passed to your view, such as:
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<SubSonic.Web.Models.Country>" %>
(in your Model, Country would have a collection of Cities - you get the drift :))
but the above would still work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With