Asp.Net MVC with Drop Down List, and SelectListItem Assistance

后端 未结 2 812
渐次进展
渐次进展 2020-12-03 01:53

I am trying to build a Dropdownlist, but battling with the Html.DropDownList rendering.

I have a class:

public class AccountTransactionView
{
    pub         


        
2条回答
  •  醉话见心
    2020-12-03 02:07

    You have a view model to which your view is strongly typed => use strongly typed helpers:

    <%= Html.DropDownListFor(
        x => x.SelectedAccountId, 
        new SelectList(Model.Accounts, "Value", "Text")
    ) %>
    

    Also notice that I use a SelectList for the second argument.

    And in your controller action you were returning the view model passed as argument and not the one you constructed inside the action which had the Accounts property correctly setup so this could be problematic. I've cleaned it a bit:

    public ActionResult AccountTransaction()
    {
        var accounts = Services.AccountServices.GetAccounts(false);
        var viewModel = new AccountTransactionView
        {
            Accounts = accounts.Select(a => new SelectListItem
            {
                Text = a.Description,
                Value = a.AccountId.ToString()
            })
        };
        return View(viewModel);
    }
    

提交回复
热议问题