So here's my situation.

Let's say I have a view called TheView.cshtml. TheView.cshtml has a ViewModel called TheViewModel.cs. In TheViewModel.cs, resides a List of an object (TheObject) called TheObjectList.

I have an editor template for TheObject called TheObject.cshtml. Using this editor template, I can simply display all of the items in the TheObjectList with @Html.EditorFor(model => model.TheObjectList).

However, now I want to dynamically add objects to this list. I have a AJAX function which calls a simple partial view to give the user a blank row to add a new "TheObject", however, any new TheObject I add dynamically is not considered part of the original TheObjectList.

This is because each item in the original TheObjectList is created with a certain prefix based on its index in the original list, whereas each new dynamic TheObject is created without a prefix, thus Razor does not see it as part of the list.

Is there a way around this?


@model Models.ViewModels.TheViewModel

<table id="Table">
        @Html.EditorFor(m => m.TheObjectList);

<button id="AddObject" type="button" class="btn btn-primary">Add Object</button>


public class TheViewModel
    public List<TheObject> TheObjectList { get; set; }

AddObject Controller Method

public IActionResult AddObject()
   return PartialView("_EmptyRow", new TheObject());

AJAX Method to Add Object

$('#AddObject').click(function () {
        url: 'AddObject',
        cache: false,
        success: function (data) {
            $('#Table > tbody').append(data);
        error: function (a, b, c) {
            alert(a + " " + b + " " + c);

Related posts

Recent Viewed