Search code examples
asp.net-mvcgeneric-collections

ASP.NET MVC View that supports adding collections of data


My application will be used for accepting/editing warranty claims. Within a warranty claim, the user can submit multiple "parts" as part of the claim. My model contains an IEnumerable<> of WarrantyParts - I've created a view model that consists of the following:

public class WarrantyClaimViewModel
{
    public int WarrantyClaimId { get; set; }

    public int UserId { get; set; }
    public DateTime DateCreated { get; set; }

    [Display(Name = "Claim Status")]
    public string Status { get; set; }

    ... other model data omitted for brevity ...

    public IEnumerable<WarrantyClaimPart> WarrantyClaimParts { get; set; }
}

My question is how do I construct a view that will allow the user to populate the collection of Warranty Parts? They could enter one or 100 individual parts; and I want to create a view where the user can click an "Add Part" button and a new set of text boxes will appear. That is, I want to dynamically add text boxes to the already existing view, not a separate view just for the warranty parts.

Would a partial view fit this requirement or should I create a separate view just for parts (not what I was looking to do, but may be the best way)? I'm looking for a best practice here. An example would be great - I like visuals.

Thank You!


Solution

  • A partial view would definitely fit what you are trying to do - you could strongly type the view to a collection of WarrantyClaimParts.

    As part of that alternative (one I like due to the UI improvement) is to use something like Knockout.js to allow for editing of the model and submit it all at once. Look at the tutorial Working with Lists and Collections as well as the tutorial Loading and Saving Data. There are some really great examples (including code!) in there that should get you exactly what you need. It's great usability and very easy to use. (per your comments, this meets your Ajax solution requirements.)