Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
294 views
in Technique[技术] by (71.8m points)

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

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

I have a class:

public class AccountTransactionView
{
    public IEnumerable<SelectListItem> Accounts { get; set; }
    public int SelectedAccountId { get; set; }
}

That is basically my view model for now. The list of Accounts, and a property for returning the selected item.

In my controller, I get the data ready like this:

public ActionResult AccountTransaction(AccountTransactionView model)
{
    List<AccountDto> accounts = Services.AccountServices.GetAccounts(false);

    AccountTransactionView v = new AccountTransactionView
    {
        Accounts = (from a in accounts
                    select new SelectListItem
                    {
                        Text = a.Description,
                        Value = a.AccountId.ToString(),
                        Selected = false
                    }),
    };

    return View(model);
}

Now the problem:

I am then trying to build the Drop down in my view:

<%=Html.DropDownList("SelectedAccountId", Model.Accounts) %>

I am getting the following error:

The ViewData item that has the key 'SelectedAccountId' is of type 'System.Int32' but must be of type 'IEnumerable'.

Why would it want me to return the whole list of items? I just want the selected value. How should I be doing this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...