Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9005441
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 16, 20262026-06-16T01:08:45+00:00 2026-06-16T01:08:45+00:00

Here is the relevant code. Mind you, I did this in Notepad++ instead of

  • 0

Here is the relevant code. Mind you, I did this in Notepad++ instead of copying in my code for my project at work. If I misspelled a class name in it, assume it is not misspelled in my code. No compile errors.

Model:

public class MyViewModel
{
    public int SelectedSomething { get; set; }

    public IList<int> Somethings { get; set; }
}

Controller:

public class MyController
{
    public ActionResult Index()
    {
        var viewModel = new MyViewModel();
        viewModel.Somethings = Enumerable.Range(1, 12).ToList();
        return View(viewModel);
    }
}

View (Razor):

@Html.DropDownListFor(x => x.SelectedSomething, new SelectList(Model.Somethings, Model.SelectedSomething), "Select an Option")

This will “work”, but won’t set values on any of the rendered option elements in the select:

<select>
    <option value="">Select an Option</option>
    <option>1</option>
    <option>2</option>
    <option>3</option>
    <option>4</option>
    <option>5</option>
    <option>6</option>
    <option>7</option>
    <option>8</option>
    <option>9</option>
    <option>10</option>
    <option>11</option>
    <option>12</option>
</select>

I know of the SelectList constructor that takes in the property names to use to render the value and text in the option elements, but it is of no use (that I can see) when using a collection of a primitive type like an int.

Question:

I know I can change my view model’s IList<int> to IList<SelectListItem>, and create SelectListItem objects to represent each int, but that seems a bit ridiculous (as I think the constructor shouldn’t leave the values blank, and should default to using the text). Am I missing something obvious here, or am I going to have to move away from using primitive types here?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-16T01:08:46+00:00Added an answer on June 16, 2026 at 1:08 am

    I solved this problem using extension methods, allowing you to write this in your views:

    @Html.DropDownListFor(x => x.SelectedSomething, 
                          Model.Somethings.ToSelectList(n => n, v => v), 
                          "Select an Option")
    

    For an int collection you may need to use n => n.ToString() as your name selector.

    The beauty of this approach is that you can use it for any kind of enumerable. In your example (with a list of integers), we simply specify lambdas that return the element itself, which will cause the text and value to be set to the same value in the rendered option list.

    If you want to avoid having to import the namespace of the extensions class in your Web.config, declare a read-only property on your ViewModel that returns the SelectList, and then access that from your view.

    The Web.config part would look something like this (note that you need to create a line for both the assembly and one for the namespace). Also note that your Views folder contains a separate Web.config that may override or extend the definitions in your root Web.config.

    <system.web>
        <compilation debug="true" targetFramework="4.0" batch="true">
            <assemblies>
                <add assembly="My.Web.Stuff" />
            </assemblies>
        </compilation>
        <pages>
            <namespaces>
                <add namespace="My.Web.Stuff.Extensions" />
            </namespaces>
        </pages>
    </system.web>
    

    This is the implementation for the extension methods:

    /// <summary>
    ///   Extension methods on IEnumerable.
    /// </summary>
    public static class SelectListExtensions
    {
        /// <summary>
        ///   Converts the source sequence into an IEnumerable of SelectListItem
        /// </summary>
        /// <param name = "items">Source sequence</param>
        /// <param name = "nameSelector">Lambda that specifies the name for the SelectList items</param>
        /// <param name = "valueSelector">Lambda that specifies the value for the SelectList items</param>
        /// <returns>IEnumerable of SelectListItem</returns>
        public static IEnumerable<SelectListItem> ToSelectList<TItem, TValue>( this IEnumerable<TItem> items, Func<TItem, TValue> valueSelector, Func<TItem, string> nameSelector )
        {
            return items.ToSelectList( valueSelector, nameSelector, x => false );
        }
    
        /// <summary>
        ///   Converts the source sequence into an IEnumerable of SelectListItem
        /// </summary>
        /// <param name = "items">Source sequence</param>
        /// <param name = "nameSelector">Lambda that specifies the name for the SelectList items</param>
        /// <param name = "valueSelector">Lambda that specifies the value for the SelectList items</param>
        /// <param name = "selectedItems">Those items that should be selected</param>
        /// <returns>IEnumerable of SelectListItem</returns>
        public static IEnumerable<SelectListItem> ToSelectList<TItem, TValue>( this IEnumerable<TItem> items, Func<TItem, TValue> valueSelector, Func<TItem, string> nameSelector, IEnumerable<TValue> selectedItems )
        {
            return items.ToSelectList( valueSelector, nameSelector, x => selectedItems != null && selectedItems.Contains( valueSelector( x ) ) );
        }
    
        /// <summary>
        ///   Converts the source sequence into an IEnumerable of SelectListItem
        /// </summary>
        /// <param name = "items">Source sequence</param>
        /// <param name = "nameSelector">Lambda that specifies the name for the SelectList items</param>
        /// <param name = "valueSelector">Lambda that specifies the value for the SelectList items</param>
        /// <param name = "selectedValueSelector">Lambda that specifies whether the item should be selected</param>
        /// <returns>IEnumerable of SelectListItem</returns>
        public static IEnumerable<SelectListItem> ToSelectList<TItem, TValue>( this IEnumerable<TItem> items, Func<TItem, TValue> valueSelector, Func<TItem, string> nameSelector, Func<TItem, bool> selectedValueSelector )
        {
            return from item in items
                   let value = valueSelector( item )
                   select new SelectListItem
                          {
                            Text = nameSelector( item ),
                            Value = value.ToString(),
                            Selected = selectedValueSelector( item )
                          };
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Here's the relevant bit of the source code: class Dice { String name ;
Here is the relevant code (doesn't work): <html> <head> <title>testing td checkboxes</title> <style type=text/css>
Here's the (relevant) code for my pro::surface class: /** Wraps up SDL_Surface* **/ class
Here is the relevant code: Canvas.cpp #ifndef CANVAS #define CANVAS #include graphicsDatatypes.h class Canvas
So I don't know why I keep getting this error. Here's the relevant code:
JSFiddle link: http://jsfiddle.net/dqkZN/32/ Here is the relevant code: <div class=categories> <h3> <img src=http://i.imgur.com/t5UXT.gif />
Here's the relevant code: <div data-bind=foreach: chats, visible: chats().length > 0> <input data-bind='value: $parent.newCommentText'
Here's the relevant code snippet. public static Territory[] assignTerri (Territory[] board, String[] colors) {
Here's the relevant code: public static void printBoarders (Territory x) { int t =
Superfish JS is here . Here's the relevant code: $.fn.extend({ hideSuperfishUl : function() {

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.