Click here to Skip to main content
15,891,204 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi All,

I am trying to figure out how to add a new 'row' in a collection in MVC4
My model contains a IList<>.
This list is looped, for every record a EditorFor is called.
Everything works fine (including posting back), except adding a new record.

I would like to collect the html of a new EditorFor with javascript and add it to my table.

Spend the last 2 hours google'ing, but cant seem to find the answer.

hope somebody has an idea :)

C#
Edit.cshtml
@using (Html.BeginForm()){
                        @for (int i = 0; i < Model.Regels_.Count; i++) {
                            @Html.EditorFor(m => Model.Regels_[i])
                        }

EditorTemplate for "Regel_" item.
<tr>
    <td>
        @Html.EditorFor(m => Model.Aantal)
    </td>
    
....etc


C#
$('#CmdAddNewRegel').click(function () {
    $.ajax({
        url: '@Url.Action("EditorTemplate??")',
        cache: false,
        success: function (html) {
            $("#TableRegels").append(html);
        }
    });


What I have tried:

I've started out without the editorTemplate.
Then I tried putting my 'row' view in a partialView.
this worked, except posting back (the partial view didn't add the [I] in the field names.
EditorFor seems the way to go, just can't figure this last part out.
Posted
Updated 11-Oct-16 2:21am
v5
Comments
F-ES Sitecore 11-Oct-16 7:07am    
If you want help modifying your code you'll need to post the relevant bits of what you have already.
w1sph 11-Oct-16 7:12am    
snippets posted :)

1 solution

Yuk..
dirty fix:

Send a counter with the Editor ViewData, use this to manualy construct the name and id of the controls.
in the Ajax call I send the HtmlTable tr count to the PartialView request.

@Html.EditorFor(m => Model.Regels_[i], new { count = i })


 string s = ViewData["count"].ToString();
 <td>
     @Html.DropDownListFor(m => Model.Btwpercentage, new SelectList(new List<int>() { 0, 6, 21 }, 21), new {
    Name = $"Regels_[{s}].Btwpercentage",
    id = $"Regels__{s}__Btwpercentage",
    type = "number"
})
 </td>


C#
public async Task<PartialViewResult> InkoopRegelRow(int? id) {
            ViewData["count"] = id;
            return PartialView("~/Views/Inkoop/EditorTemplates/InkoopOrderRegel.cshtml", new InkoopOrderRegel());
        }
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900