Sarmad Mirza
Sarmad Mirza

Reputation: 35

How to get selected value in dropdown in asp.net core 2.2?

I want to get the selected value in the dropdown when getting the data from database.

I have tried using:

<option value="" style="font-size:medium; font-weight:bold; ">
    Select Action
</option>
<option value="Sent To Dhoobi" 
  selected="@(item.Suit_Status == "Sent To Dhoobi" ? "selected" : "")">
    Sent To Dhoobi
</option>
<option value="Sent For Cutting" 
  selected="@(item.Suit_Status == "Sent For Cutting" ? "selected" : "")">
    Sent For Cutting
</option>
<option value="In Rack" 
  selected="@(item.Suit_Status == "In Rack" ? "selected" : null)">
    In Rack
</option>
<option value="Delivered" 
  selected="@(item.Suit_Status == "Delivered" ? "selected" : null)">
    Delivered
</option>

I want to get the selected value in the dropdown but cannot get the value.

Upvotes: 1

Views: 6012

Answers (1)

David Liang
David Liang

Reputation: 21476

Can you change the way you build that dropdown? You can define a property for the selected suit status and a list of available suit statuses in the view model, and build the dropdown on the view with tag helpers.

View model

// I just make up the name
public class UpdateSuitViewModel
{
    [Required]
    [Display(Name = "Status")]
    public string SelectedSuitStatus { get; set; }

    public IEnumerable<string> AvailableSuitStatuses { get; set; }
}

Controller

In the controller, you can build the view model with the data from the database:

public IActionResult Edit()
{
    // Get the statues from the database
    var suitStatuses = ...    

    var vm = new UpdateSuitViewModel
    {
        AvailableSuitStatuses = suitStatuses
    };

    return View(vm);
}

View

@model UpdateSuitViewModel

<form>
    <select class="form-control"
        asp-for="SelectedSuitStatus"
        asp-items="new SelectList(Model.AvailableSuitStatuses)">
        <option value="">Select Action</option>
    </select>
</form>

The tag helper for the dropdown from ASP.NET CORE will help you build the dropdown with the name SelectedSuitStatus and dropdown options from AvailableSuitStatuses;

When you post the form back, the view model SelectedSuitStatus will contain the selected dropdown option value!

Upvotes: 2

Related Questions