Search code examples
c#razorasp.net-core-mvcmodel-bindingselectlist

How do you get a selected item on post from a select list with only text item in asp.net core mvc?


How do you get a selected item value or text on post from a select list with only text items in asp.net core mvc?

The model has one string property, ChosenText.

Currently, ChosenText always comes back in the post action method as null.

The markup:

<form asp-action="MakeChange" method="post" id="mainform">
  <select name="cars" id="cars" asp-for="ChosenText">
        <option value="volvo">Volvo</option>
        <option value="saab">Saab</option>
        <option value="mercedes">Mercedes</option>
        <option value="audi">Audi</option>
    </select>
   <button type="submit">Submit</button>
</form>

Action method:

    [HttpPost]
    [ValidateAntiForgeryToken]
    public IActionResult MakeChange(TestModel model)
    {
        if (model.ChosenText.ToUpper() == "VOLVO")
        {

        }

        return View(model);
    }

Solution

  • Currently, ChosenText always comes back in the post action method as null.

    Please note that asp-for="ChosenText" will help generate name and id attribute for rendered html <select> tag automatically.

    In your code, we can find that you also explicitly specify name="cars" and id="cars" for Select Tag Helper. To make your posted data can be bound to model property as expected, please check if your model class and property are defined as below.

    public class TestModel
    {
        [BindProperty(Name = "cars")]
        public string ChosenText { get; set; }
    
        //...
        //other properties
        //...
    

    Besides, to troubleshoot the similar issues, you can check the actual request with posted data, and compare the posted data with your model properties.