Steven
Steven

Reputation: 18859

Do something on Page Load in 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.

Upvotes: 4

Views: 4740

Answers (3)

jim tollan
jim tollan

Reputation: 22485

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.

Upvotes: 3

Rony
Rony

Reputation: 9511

public class HomeController : Controller
{
    public ActionResult Index()
    {
        var cities = <data access code>

        return View(cities);
    }
}

@ Page Title='' Language='C#' MasterPageFile='~/Views/Shared/Site.Master' Inherits=System.Web.Mvc.ViewPage<IEnumerable<City>> 

<select id="ddlCities">
    <% foreach (var item in ViewData.Model.Cities) { %>
        <option value='<%= item.CityID %>'><%= item.CityName %></option>
    <% } %>
</select>

Upvotes: 2

Henrik P. Hessel
Henrik P. Hessel

Reputation: 36617

You should take a look into Action Filters.

You can overwrite methods of the ActionFilterAttribute class for different states of an "action" life cycle.

OnActionExecuting – This method is called before a controller action is executed.
OnActionExecuted – This method is called after a controller action is executed.
OnResultExecuting – This method is called before a controller action result is executed.
OnResultExecuted – This method is called after a controller action result is executed.

Upvotes: 3

Related Questions