Share via


Validation DropDownList value from ViewModel in ASP.Net MVC

Question

Saturday, November 21, 2020 9:40 AM

Hi, I need your help

I tried to search posts, without any result either, maybe I didn't use the right words.

I need a solution in MVC for validate the DropDownList value, populated from database using Model class and the Html.DropDownListFor Helper method and MySql.

In the view I have added new DDL and this is populated correctly from database

    @Html.DropDownListFor(m => m.Fruits, Model.Fruits, "[ === Please select === ]", new { @Class = "textarea" })
    @Html.ValidationMessageFor(m => m.Fruits, "", new { @class = "text-danger" })

    <div class="form-group">
        <div class="col-md-offset-5 col-md-10">
            <input type="submit" value="Create" class="btn btn-default" />
        </div>
    </div>

But when on click the

<input type="submit" value="Create" class="btn btn-default" />

The form is validate and does not stop sending when the DDL has not selected any value.

Without DDL the validation working correctly.

Please, help me.

My code below

Model

namespace InsGE.Models
{
    public class PersonModel
    {
        [Required]
        [Display(Name = "Fruits")] 
        public List<SelectListItem> Fruits { get; set; }

        public string Namex { get; set; }
        
        public string Codex { get; set; }

        [Required]
        [Display(Name = "CL")] 
        public string CL { get; set; }

        [Required]
        [Display(Name = "Ticket")]
        public string Ticket { get; set; }
    }
}

Controller

namespace InGE.Controllers
{
    public class HomeController : Controller
    {
        private static List<SelectListItem> PopulateFruits()
        {
            string sql;

            List<SelectListItem> items = new List<SelectListItem>();

            string constr = ConfigurationManager.ConnectionStrings["cn"].ConnectionString;

            using (MySqlConnection con = new MySqlConnection(constr))
            {
                sql = @String.Format("SELECT * FROM `dotable`; ");

                using (MySqlCommand cmd = new MySqlCommand(sql))
                {
                    cmd.Connection = con;
                    con.Open();

                    using (MySqlDataReader sdr = cmd.ExecuteReader())
                    {
                        while (sdr.Read())
                        {
                            items.Add(new SelectListItem
                            {
                                Text = sdr["sName"].ToString(),
                                Value = sdr["sCode"].ToString()
                            });
                        }
                    }
                    con.Close();
                }
            }

            return items;
        }

        [HttpPost]
        public ActionResult Index(PersonModel person)
        {
            string sCl = person.CL;
            string sTicket = person.Ticket;       
            string sName = person.Namex;
            string sCode = person.Codex;

            return View();
        }

        [HttpGet]
        public ActionResult Index()
        {
            PersonModel fruit = new PersonModel();
            fruit.Fruits = PopulateFruits();
            return View(fruit);
        }

        public ActionResult About()
        {
           ViewBag.Message = "Your application description page.";    
           return View();
        }

        public ActionResult Contact()
        {
           ViewBag.Message = "Your contact page.";    
           return View();
        }

All replies (1)

Saturday, November 21, 2020 2:55 PM âś…Answered

You did not add the [Required] annotation to the input field.

namespace MvcBasic.Controllers
{
    public class ViewModel
    {
        public List<SelectListItem> Options { get; set; }
        [Required]
        public int SelectedOption { get; set; }
    }
    public class BasicFormsController : Controller
    {
        // GET: BasicForms
        [HttpGet]
        public ActionResult Index()
        {
            ViewModel vm = new ViewModel()
            {
                Options = PopulateOptions()
            };

            return View(vm);
        }

        [HttpPost]
        public ActionResult Index(ViewModel model)
        {
            ViewModel vm = new ViewModel()
            {
                Options = PopulateOptions(),
                SelectedOption = model.SelectedOption
            };
            ViewBag.Message = $"You selected value {model.SelectedOption}";
            return View(vm);
        }

        private List<SelectListItem> PopulateOptions()
        {
            return new List<SelectListItem>()
             {
                  new SelectListItem()
                  {
                      Text = "Option 1",
                      Value = "1"
                  },
                  new SelectListItem()
                  {
                      Text = "Option 2",
                      Value = "2"
                  },
                  new SelectListItem()
                  {
                      Text = "Option 3",
                      Value = "3"
                  }
             };
        }
    }
}

@model MvcBasic.Controllers.ViewModel
@{
    ViewBag.Title = "Index";
}

<h4>Index</h4>

<form method="post">
    <div>
        @Html.DropDownListFor(m => m.SelectedOption, Model.Options, "--Select--")
        @Html.ValidationMessageFor(m => m.SelectedOption, "", new { @class = "text-danger" })
    </div>
    <div>
        <input id="Submit1" type="submit" value="submit" />
    </div>
</form>


@if(!string.IsNullOrEmpty(ViewBag.Message)) {
    <div>
        @ViewBag.Message
    </div>
}

It seems you are having trouble with MVC model binding and/or HTML forms.  I recommend taking the time to go through the tutorials I provided in your other thread with the same subject.  The tutorials cover fundamental MVC programming patterns which should help you better design MVC solutions.