In MVC: Copy view elements by jQuery and retrive v

2019-06-07 04:07发布

问题:

This is my view:

@model PhoneBook.Models.Number
@{
ViewBag.Title = "Create";
}
<h2>Create</h2>
<script src="../../Scripts/jQuery.AddNewNumber.js" type="text/javascript"></script>
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
@Html.HiddenFor(model => model.Contact.Id)
<fieldset>
    <legend>Number</legend>
    <div class="TargetElements">
        <div class="editor-label">
            @Html.LabelFor(model => model.PhoneNumber)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.PhoneNumber)
            @Html.ValidationMessageFor(model => model.PhoneNumber)
        </div>
        <div class="editor-label">
            @Html.LabelFor(model => model.NumberKind)
        </div>
        <div class="editor-field">
        @Html.DropDownListFor(model => model.NumberKind.Title, NumberKinds)
        </div>
    </div>
<p>
        <input class="AddNew" value="Add New" type="button" /></p>
    <p>
        <input type="submit" value="Create" />
    </p>
</fieldset>
}

I need when press the "Add New" button All the elements in <div class="TargetElements"> Copied and in when press the submit button I can achieve all values.

At now i use this script:

$(document).ready(function () {
$('.AddNew').click(function () {
    $(".TargetElements:first").clone().insertAfter('.TargetElements');
});
});

but there is 2 problem with this: 1- when I add first time one div(include target elements) added but in second time two div added and grow in ascending 2- when copy the elements all the value of target element added but I need Empty inputs to add new value

How Can I fix the Script?

And finally I don't know how can I retrieve values of all element in my controller:

[HttpPost]
    public ActionResult Create(Number NewNumber, FormCollection collection) {
}

回答1:

1- when I add first time one div(include target elements) added but in second time two div added and grow in ascending.

You insert the new field after every field that exist, take a look at: $(".TargetElements:first").clone().insertAfter('.TargetElements');

Should be: $(".TargetElements:first").clone().insertAfter('.TargetElements:last');

2- when copy the elements all the value of target element added but I need Empty inputs to add new value

There is no one that stops you from clearing the values with Javascript, just go through all the input elements in the new clone and clear their values.

function cloneTargetBox() {
    var targetBoxClone = $(".target-elements:first").clone();
    targetBoxClone.find("input").val(""); //Not sure this is the proper way, but hey, it works
    targetBoxClone.insertAfter(".target-elements:last")
}

Here is a code sample of what you want to achieve: http://jsfiddle.net/KVqW8/3/