title: ASP.NET CORE Dropdown List Validation
body: <p>I am using <code>ViewBag</code> to populate dropdown list in my razor view page in ASP.NET Core MVC form. I tried to set up an initial value, ie. <code>Text=&quot;Select&quot;</code>, <code>Value=&quot;&quot;</code>, so if user selects the default value, the form will show error message. I tried to set default value in model class but the validation does not work when user skips dropdown list. Please advise.</p>
  <p>Model class:</p>
  <pre><code>myClass
  {
      [StringLength(250)]
      [Required]
      public string lunch { get; set; } = String.Empty;
  }
  </code></pre>
  <p>Controller:</p>
  <pre><code>public IActionResult Create()
  {
      List&lt;SelectListItem&gt; lunch = new List&lt;SelectListItem&gt;
              {
                  new SelectListItem{Value=&quot;No lunch&quot;, Text=&quot;No lunch&quot;},
                  new SelectListItem{Value=&quot;Turkey Sandwitch&quot;, Text=&quot;Turkey Sandwitch&quot;}
                  new SelectListItem{Value=&quot;Vegie Sandwitch&quot;, Text=&quot;Vegie Sandwitch&quot;}
              };
  
      lunch.Insert(0, new SelectListItem { Value = String.Empty, Text = &quot;Select&quot; });
  
      ViewBag.lunch = lunch;
  
      return View();
  }
  </code></pre>
  <p>View:</p>
  <pre><code>&lt;div class=&quot;form-group&quot;&gt;
      &lt;label asp-for=&quot;lunch&quot; class=&quot;control-label&quot;&gt;&lt;/label&gt;
      @Html.DropDownList(&quot;lunch&quot;,  new SelectList(ViewBag.lunch,&quot;Value&quot;,&quot;Text&quot;))       
      &lt;span asp-validation-for=&quot;lunch&quot; class=&quot;text-danger&quot;  &gt;&lt;/span&gt;
  &lt;/div&gt;
  </code></pre>