简体   繁体   中英

Dropdown asp.net core Set selected item

i need to set selected item in dropdown

<div class="form-group">
    <label asp-for="Transaction.CCurrency" class="control-label"> Currency </label>

    @(Html.DropDownList("CurrencyDropDownList", Model.Currency, "--Choose currency--", new { @class = "form-control" }))

    <span asp-validation-for="CurrencyDropDownList" class="text-danger"></span>
</div>

I am filling it in controller

model.Currency = database.ZCurrency.Where(x => x.LActive == true).Select(c => new SelectListItem
                 {
                     Value = c.CCode.ToString(),
                     Text = c.CName,
                 });

This is in my view model

public IEnumerable<SelectListItem> Currency { get; set; }

However, i have no idea how to set it from my database, i can get to CCode and to Cname through it, but not how to set it. This is in my EDIT form, where i need to see which value i had before and re-set it on another if needed.

Thank you very much, would appreciate any help.

You can just set the selected property as true in the SelectListItem, which will make this option selected by default in the page. I made a simple demo based on your codes like below:

View:

<div class="form-group">

    @(Html.DropDownList("CurrencyDropDownList", Model.Currency, "--Choose currency--", new { @class = "form-control" }))

</div>

Model:

public class ZCurrency
{
    public int CCode { get; set; }
    public string CName { get; set; }
}

public class ViewModel
{
    public IEnumerable<SelectListItem> Currency { get; set; }
}

Controller:

public IActionResult Index()
    {
        List<ZCurrency> currencies = new List<ZCurrency>
        {
            new ZCurrency{ CCode = 1, CName = "AAA" },
            new ZCurrency{ CCode = 2, CName = "BBB" },
            new ZCurrency{ CCode = 3, CName = "CCC" },
        };
        ViewModel viewModel = new ViewModel();
        viewModel.Currency = currencies.Select(c => new SelectListItem
        {
            Value = c.CCode.ToString(),
            Text = c.CName,
            Selected = c.CCode == 2 ? true: false
        });

        return View(viewModel);
    }

Here, I set the record which CCode is 2 (new ZCurrency{ CCode = 2, CName = "BBB" }) as the selected item by setting Selected as true.

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