0

I have a view like this:

<div class="editor-label">
    @Html.LabelFor(model => model.Parts)
</div>
<div class="editor-field">
    <ul id="parts"></ul>
    <span id="parts-button" onclick="addPart()">+ Add part</span>
</div>

, a JS like so:

function addPart(name) {
    var input = $('<input>').attr("name", "Parts");

    if (name != null)
        input.val(name);

    $('<li>')
        .append(input)
        .append($('<div>')
            .html("X")
            .on("click", function () {
                var div = $(this)
                div.parent().slideUp(function () { $(this).remove(); });
            })
            .addClass("delete"))
        .appendTo($('#parts')).hide().slideDown();
}

and a model like this:

public virtual IList<string> Parts { get; set; }

My question is; is it's possible to populate the models list of strings directly from the dynamic number of elements in the view. Or do I have to do the following:

public ActionResult Create(Model model, IList<string> Parts)
{
    model.Parts = Parts;

Any help or link to relevant information is highly appreciated. I have been searching, but am unable to find relevant information about this sort of problem.

tereško
  • 58,060
  • 25
  • 98
  • 150
Robin Dorbell
  • 1,569
  • 1
  • 13
  • 26
  • 1
    See this answer [Generate list in view and pass it to controller](http://stackoverflow.com/questions/15742868/generate-list-in-view-and-pass-it-to-controller) – user1477388 Mar 21 '14 at 15:00

1 Answers1

0

Thanks to this questions answer: Generate list in view and pass it to controller I figured out that if you change name of input to include and index ([i]) it passes the string correctly.

Solution:

While creating input I changed the javascript to code to the following:

var input = $('<input>').attr("name", "Parts[" + index + "]");
Community
  • 1
  • 1
Robin Dorbell
  • 1,569
  • 1
  • 13
  • 26