0

Cant bind it from database so can hard coded it but wanna bind it through loop.

One way.

 @Html.DropDownListFor(m => m.Age, new List<SelectListItem> { new SelectListItem 
            { Text = "1", Value = "1" }, new SelectListItem 
            { Text = "10", Value = "10" } }, "select")

From 1 to 10 dont wanna do this,so doing it through for loop. In Action

                var list = new List<int>();
            for (int i = 1; i <= 10; i++)
            {
                list.Add(i);
            }

            SelectList selectedList = new SelectList(list);
            ViewBag.DdList = selectedList;

On Index View

    <tr>
        <td>
            DDL
        </td>
        <td>
            @Html.DropDownListFor(model => model.Age, ViewBag.DdList as  SelectList, "Select")
        </td>
    </tr>

Here it works fine but on Edit View if I select any value then i get

The ViewData item that has the key 'Age' is of type 'System.Int32' but must be of type 'IEnumerable

Model

 public Nullable<int> Age { get; set; }

Have understood that the data type is of int and it expects Select item. How do I convert int to Selectlist item.

Tried

 var list = new List<SelectList>();
            for (int i = 1; i <= 10; i++)
            {
                list.Add(i);
            }

Conversion error.

Dave
  • 263
  • 6
  • 23
  • You need to build a SelectList based on a List of SelectListItem, not a List of Integers. – Renato Saito Feb 21 '16 at 16:41
  • Hi have tried that you can see under Tried section but have to pass int in loop as Data text field and Data Value field is going to be int. – Dave Feb 21 '16 at 16:45
  • You mean after selecting an item on edit screen and submitting the form ? Can you show us your code for your HttpPost action method ? – Shyju Feb 21 '16 at 22:18
  • 1
    And you can simplify the code to `ViewBag.DdList = new SelectList(Enumerable.Range(1, 10));` –  Feb 21 '16 at 22:21

0 Answers0