'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);
}
Solution 1:[1]
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!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | João Pereira |
