0

I am new to .NET MVC and am trying to figure out forms, I think I am on the right track but I am stuck trying to figure out how to create a form based off of a class that has an ObservableCollection<> of another class, for example:

public class Items
{
    public string Notes { get; set; }
    public ObservableCollection<LineItem> LineItems { get; set; }
}

and Line Items is something like:

public class LineItem
{
    public string ItemNumber { get; set; }
    public string QTY { get; set; }
}

From what I understand I should create an instance of Items in the controller and pass that to my view

return View(new Items());

Then on my view I use HTML helpers to create the form and when I submit the form, the model Items is sent back to the controller with filled out data. How do I go about having multiple LineItems in my view that bind to the ObservableCollection<> in my Model ? Let's say they need 2 LineItems, is there a programmatic way to show the inputs for public ObservableCollection<LineItem> LineItems multiple times, as an ObservableCollection is typically more than one instance of the class. I am using .NET MVC C# with Razor syntax.

Craig W.
  • 16,585
  • 6
  • 44
  • 77
user4612487
  • 267
  • 1
  • 3
  • 14
  • To render controls for collections you use a `for` loop - `for(int i = 0; i < Model.LineItems.Count; i++) { @Html.TextBoxFor(m => m.LineItems[i].ItemNumber) }` or create a custom `EditorTemplate for typeof `LineItem`. –  Feb 26 '15 at 23:53
  • Here is one approach http://stackoverflow.com/a/26284038/84206 and here is a different approach http://stackoverflow.com/a/15375949/84206 – AaronLS Feb 27 '15 at 00:22
  • @AaronLS these answers only seem to cover showing data that already exists in the class that is passed to the View, I am trying to create a new entry. – user4612487 Feb 27 '15 at 14:10
  • @user4612487 Creating a form for existing items and creating a form for new items is somewhat similar though. You simply need to follow the same square brackets patterns for the HTML `name`, but instead of generating the HTML from Razor, you'd generate it dynamically with javascript when user clicks something like + button to add a new line form. – AaronLS Feb 27 '15 at 15:55
  • @user4612487, [This answer](http://stackoverflow.com/questions/28019793/submit-same-partial-view-called-multiple-times-data-to-controller/28081308#28081308) shows some options for dynamically adding new items to a collection. –  Feb 28 '15 at 03:41

0 Answers0