Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do something on Page Load in ASP.NET MVC

Tags:

c#

asp.net-mvc

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.

like image 504
Steven Avatar asked Feb 27 '23 03:02

Steven


1 Answers

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.

like image 81
jim tollan Avatar answered Mar 11 '23 03:03

jim tollan