Mizanur Rahaman
Mizanur Rahaman

Reputation: 453

How to pass any selected option value from a view to a controller ASP.NET Core

This is my code. I want to select a option and pass the value in controller.

                    <div class="form-group">
                        <label asp-for="MobileNumber" class="control-label">Mobile Number</label>
                        <input asp-for="MobileNumber" class="form-control" />
                        <span asp-validation-for="MobileNumber" class="text-danger"></span>
                    </div>

                    <div class="form-group">
                         <label asp-for="Gender" for="inputState">Gender</label>
                          <select asp-for="Gender" id="inputState" class="form-control">
                            <option selected>Please Choose...</option>
                            <option>Male</option>
                            <option>Female</option>
                            <option>Other</option>
                          </select>
                    </div>

This is Controller Action. I want to get select option value this action.

    [HttpPost, ValidateAntiForgeryToken]
    public async Task<IActionResult> Create(CreateModel model)
    {
        if (ModelState.IsValid)
        {
            try
            {
                model.Resolve(_scope);
                await model.UserCreate();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "User not create.");
            }
        }
        return View(model);
    }

Upvotes: 0

Views: 3471

Answers (1)

Jo&#227;o Pereira
Jo&#227;o Pereira

Reputation: 1667

Not sure about the full context of the CreateModel object, specifically what type is Gender, but I'm assuming it's string. One thing that you are missing is defining values for the select options.

You need to do something similar to this in order to give a value for each option:

<select asp-for="Gender" id="inputState" class="form-control">
    <option selected>Please Choose...</option>
    <option value="Male">Male</option>
    <option value="Female">Female</option>
    <option value="Other">Other</option>
</select>

Let me know if it helped!

Upvotes: 1

Related Questions