Filling in the SelectList with a for loop

2019-09-03 05:39发布

Ok, my drop down used to be made like so:

<select id="Level" onchange="showChoice(this.value);">
     <option id="0" value="0">Pick a Level</option>
     @for (int i =1; i <= Model.ExamplesCount; i++ )
     {
         <option id="@i" value="@i">Level @i</option>
      }
</select>

because the ExamplesCount number changes per user. But I need to use the Html.ValidationMessageFor() thing, which I can't get to work with this.

I need one of two solutions.

  1. Can I make Html.ValidationMessageFor() work with this select tag?

or if not,

2.Can I use Html.DropDownListFor() but fill it in with a similar for loop?

For example,

@Html.DropDownListFor(
    m => m.Level, 
    new SelectList(
        new List<Object> {
             new {value = 0, text ="Pick a Level"},
             new { value = 1, text = "Level 1"},
             new { value = 2, text = "Level 2" },
             new { value = 3, text = "Level 3" },
             new { value = 4, text = "Level 4" },
             new { value = 5, text = "Level 5" } 
        },
     "value", "text", null))
 @Html.ValidationMessageFor(model => model.Level)

The above code works, but where I am hard coding all the SelectList values, I'd like to have an for loop that does it for me.

1条回答
贼婆χ
2楼-- · 2019-09-03 06:02

What about creating a object in your model that will content all the items you want an then pass that to your view? Example:

In your Model.

public class Model{
     ...other properties
    public List<ListItemSource> myLevels { get; set; }
    [Required(ErrorMessage = @"*Required")]
    public string Level { get; set; }
}

In your controller:

public ActionResult YourAction(Model myModel)
    {
        var myModel = new Model
        {
            myLevels =methodToGetLevels()                
        };

        return view(myModel);
    }

In your View:

   @Html.DropDownListFor(x => x.Level,
                         new SelectList(Model.myLevels, "Value", "Text"))

    @Html.ValidationMessageFor(model => model.Level)

Where x.Level will hold the selected value and Model.myLevels is the collection of levels. I hope this help to solve your problem.

查看更多
登录 后发表回答