简体   繁体   中英

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);
    }

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM