1

I am new to MVC framework and cant figure out how to populate a dropdown list which binds with the database.Please help me in the view part as I want to show the Account Name in dropdown list using the following code.

Model:-

[Table("account")]
public class Accounts
{
    [Key]
    public int acc_id { get; set; }
    public string acc_name { get; set; }
    // public SelectList AccountList { get; set; }  
}

AccountsContext

public class AccountsContext:DbContext
{
    public DbSet<Accounts> Account { get; set; }
    // public SelectList Accounts { get;set;}
}

Controller:-

public ActionResult Group()
{
    Accounts ak = new Accounts();
    AccountsContext accountscontext = new AccountsContext();
    List<Accounts> account = accountscontext.Account.ToList();
    return View(account);
}
ekad
  • 14,436
  • 26
  • 44
  • 46
  • Show your view (and you need to return a model containing a property to bind to (say) `int SelectedAccount` and a property for the options (say) `IEnumerable AccountList` –  Aug 23 '16 at 05:31
  • Stephen I used this code in my view. @model IEnumerable – Subhodeep Bhattacharjee Aug 23 '16 at 05:33
  • What code in your view (you have not shown your view) –  Aug 23 '16 at 05:34
  • I have not written any code for dropdown in the view part. model IEnumerable @{ ViewBag.Title = "Group"; Layout = "~/Views/Shared/_Layout.cshtml"; } These are the initials that my view contains.next thing I need to do is to populae the dropdown here. – Subhodeep Bhattacharjee Aug 23 '16 at 05:39
  • I suggest to read [this question/answer](http://stackoverflow.com/questions/34366305/the-viewdata-item-that-has-the-key-xxx-is-of-type-system-int32-but-must-be-o) to learn the basics –  Aug 23 '16 at 05:41

1 Answers1

0

You are sending the list of accounts as model to your view. That's fine. But how are you going to get the value that the user would select? For that you should have a property at you server side binded to the selected item at client-side.

I would suggest using a ViewModel which would have the list of accounts as collection of SelectListItem (which would be populated in the controller) and another property for the selected item and then instead of passing the list of accounts directly to your view you should pass the new viewModel and bind accordingly.

ViewModel

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

View

@model AccountsViewModel
@Html.DropDownListFor(m => m.SelectedAccountId , Model.Accounts)