Search code examples
asp.net-mvclistasp.net-coreview

asp.net core mvc add item to exiting model in View


ASP.NET Core 2 MVC web app.

I have a page that inherit from a model and shows data that has to be modified. That model has a List<> that is render using a foreach

Here is my model

public class ParticipantModel
    {
        public List<ParticipantSpecificFieldsModel>? ParticipantSpecificFieldsModel { get; set; }
    }

public class ParticipantSpecificFieldsModel
{
      public string? FieldName { get; set; }
     public string? FieldValue { get; set; }
}

In the Page I have this

 @foreach (var participantSpecifiFields in Model.ParticipantModel)
        {
            <div style="float:left; width:80%;">
                <div class="col-2" style="float:left;">
                    <span style="font-weight:bold;">@participantSpecifiFields.FieldName</span>
                </div>
                <div class="col-2" style="float:left;">
                    <span>@participantSpecifiFields.FieldValue</span>
                </div>
            </div>
        }

I need to Submit the form and I was thinking to use

<form action="@Url.Action("Update", "Client")" id="formUpdate" enctype="multipart/form-data" method="post">

The problem I have is that, apart from updated existing items, I can add a new one.

I tried with

<div class="col">
            @Html.EditorFor(model => model.ParticipantSpecificFieldsModel![X].FieldName, new { htmlAttributes = new { @class = "form-control" } })
        </div>
        <div class="col">
            @Html.EditorFor(model => model.ParticipantSpecificFieldsModel![X].FieldValue, new { htmlAttributes = new { @class = "form-control" } })
        </div>

Where X is the last index +1. But does not work.

If there a way to add Items to an existing Model? and send it to Controller when I submit?

Thanks


Solution

  • As Mr pcalkins said, you can use EditorFor(xxx) for something doesn't exist, So here, I think you can set a button, When user click the button, use JavaScript to generate an input element for user to input the value of FieldName and FieldValue. Here is a simple demo. Hope it can give you some help.

    Controller

          //For testing, I just hard code here.
            ParticipantModel model = new ParticipantModel()
            {
                ParticipantSpecificFieldsModel = new List<ParticipantSpecificFieldsModel>()
                {
                    new ParticipantSpecificFieldsModel()
                    {
                        FieldName ="AAA",
                        FieldValue = "aaaaa"
                    },
                    new ParticipantSpecificFieldsModel()
                    {
                        FieldName ="BBB",
                        FieldValue = "bbbbb"
                    },
                    new ParticipantSpecificFieldsModel()
                    {
                        FieldName ="CCC",
                        FieldValue = "ccccc"
                    },
                    new ParticipantSpecificFieldsModel()
                    {
                        FieldName ="DDD",
                        FieldValue = "ddddd"
                    }
                }
            };
    
    
            public IActionResult Hello()
            {
                return View(model);
            }
    

    View

    @model ParticipantModel
    
    <form method="post">
        <div data="@Model.ParticipantSpecificFieldsModel.Count()" id="count"></div>
        @for (var i = 0;i<Model.ParticipantSpecificFieldsModel.Count();i++)
        {
            <div style="float:left; width:80%;">
                <div class="col-2" style="float:left;">
                    <span style="font-weight:bold;">@Model.ParticipantSpecificFieldsModel[i].FieldName</span>
                    <input type="hidden" name="ParticipantSpecificFieldsModel[@i].FieldName" value="@Model.ParticipantSpecificFieldsModel[i].FieldName" />
                </div>
                <div class="col-2" style="float:left;">
                    <span>@Model.ParticipantSpecificFieldsModel[i].FieldValue</span>
                    <input type="hidden" name="ParticipantSpecificFieldsModel[@i].FieldValue" value="@Model.ParticipantSpecificFieldsModel[i].FieldValue" />
                </div>
            </div>
        }
        <br />
        <div id="new-fields-container"></div>
        <br />
        <button id="add-field" type="button">Add Field</button>
        <br />
        <button type="submit">Submit</button>
    </form>
    
    @section Scripts{
        <script>
            $('#add-field').click(function () {
    
                var newIndex = document.getElementById("count").getAttribute('data')
                var newHtml = '<div class="col">' +
                    '<input type="text" name="ParticipantSpecificFieldsModel[' + newIndex + '].FieldName" class="form-control" />' +
                    '</div>' +
                    '<div class="col">' +
                    '<input type="text" name="ParticipantSpecificFieldsModel[' + newIndex + '].FieldValue" class="form-control" />' +
                    '</div>';
                $('#new-fields-container').append(newHtml);
                
            });
        </script>
    }
    

    Demo

    enter image description here