Search code examples
asp.net-mvcasp.net-mvc-viewmodel

ASP.NET MVC - Display additional data in a View


I have a View that displays a "grid" of all the Payments, which works fine.

Now, I would like to also add an additional dropdown to that View with the list of the Merchants.

How should I go about it? Add another field in my PaymentViewModel to have a list of the Merchants? Create two models? Can I create a partial view for just the dropdownlist and bind it another model?

I'm new to MVC so any thoughts are welcome.

Payments.cshtml

@model IEnumerable<MVC.Web.Models.PaymentsViewModel>

PaymentsViewModel.cs

public int PaymentID { get; set; }
public string Merchant { get; set; }

Solution

  • If you want one dropdown for the entire view, then you wouldn't add the list to PaymentsViewModel, as that would be adding a dropdown for each payment. Also this viewmodel should have a singular name because each represents a single item: PaymentViewModel.

    Payments.cshtml

    @model PaymentsViewModel
    
    @Html.DropDownFor(... Model.Merchants...)// select into ListItems
    
    <table>...
    foreach(PaymentViewModel payment in Model.Payments)
        ...your existing "grid"
    

    PaymentViewModel.cs

    public int PaymentID { get; set; }
    public string Merchant { get; set; }
    

    PaymentsViewModel.cs

    List<MerchantsViewModel> Merchants {get;set;}
    List<PaymentViewModel> Payments {get;set;}
    

    Alot of how I would go about this depends on what you are trying to accomplish with this dropdown though.