Search code examples
asp.net-mvcmodel-view-controllerasp.net-mvc-layout

What is the right approach to initialize the Model's data inside of the mvc layout page and bind it to the dropdown list?


Currently, I'm doing the following logic:

I have a Layout page where I need to display a Kendo.DropDown list.

I have created a Model:

public class CultureModel { public string Culture { get; set; }

public List<string> AvailableCultures { get; set; }

public CultureModel()
{
    PopulateCulture();
}

private void PopulateCulture()
{
    CultureModel cm = new CultureModel();
    cm.AvailableCultures = new List<string>();
    cm.AvailableCultures.Add("en-US");
    cm.AvailableCultures.Add("de-DE");
    cm.AvailableCultures.Add("es-ES");
}

}

And in my Layout I define the model: @model CultureModel

Then, I'm trying to render DisplayTemplate to show the dropdown:

 @Html.DisplayFor(x => x.AvailableCultures, "_CultureSelector")

And my template is:

@model List<string>

<label for="culture">Choose culture:</label>
@(Html.Kendo().DropDownList()
        .Name("culture")
)

Is that correct approach?


Solution

  • Thinking about your usecase by having a dropdown in the layout file, it would be fine to create your kendo dropdown with the following code directly in the layout file:

    @{
     @(Html.Kendo().DropDownList()
          .Name("Cultures")
          .DataTextField("Text")
          .DataValueField("Value")
          .BindTo(new List<SelectListItem>() {
              new SelectListItem() {
                  Text = "en-US",
                  Value = "1"
              },
              new SelectListItem() {
                  Text = "de-DE",
                  Value = "2"
              },
              new SelectListItem() {
                  Text = "es-ES",
                  Value = "3"
              }
          })
       )
    }
    

    Perhaps use a partialview to render the code in the layout for better code organizing and readability: @Html.Partial("_CultureSelector")

    I found the code on the telerik site: https://demos.telerik.com/aspnet-mvc/dropdownlist