I'm trying to add and remove form fields in MVC Asp.Net. I've followed this tutorial of dynamic adding and removing form fields.
I'm having a problem only this part of code. In below code it only adds a textbox.
if(x < max_fields){ //max input box allowed
x++; //text box increment
$(wrapper).append('<div><input type="text" name="mytext[]"/><a href="#" class="remove_field">Remove</a></div>'); //add input box
}
});
but I want to add 2 dropdownlists and 1 textbox by using MVC helpers not html codes.
I've 2 dropdownlist, Sizes and Colors and 1 textbox for Quantity. Dropdownlists are populating values from DB.
<div class="form-group">
<div class="row">
<div class="input_fields_wrap">
<button class="add_field_button">Add More Fields</button>
<div class="col-md-2">
@Html.DropDownList("ProductSizeVariantId", null, "Size", new { @class = "control-label" })
</div>
<div class="col-md-2">
@Html.DropDownList("ProductSizeVariantValueId", null, "Select Size", new { @class = "control-label" })
</div>
<div class="col-md-2">
@Html.DropDownList("ProductColorVariantId", null, "Select Color", new { @class = "control-label" })
</div>
<div class="col-md-2">
@Html.TextBoxFor(x => x.Stock, new { @placeholder = "Quantity", @class = "form-control" })
</div>
</div>
</div>
</div>
here is what i've tried
$(wrapper).append('<div><div class="col-md-2">@Html.DropDownList("ProductSizeVariantId", null, "Size", new { @class = "control-label" })</div><div class="col-md-2">@Html.DropDownList("ProductSizeVariantValueId", null, "Select Size", new { @class = "control-label" })</div><div class="col-md-2">@Html.DropDownList("ProductColorVariantId", null, "Select Color", new { @class = "control-label" })</div><div class="col-md-2">@Html.TextBoxFor(x => x.Stock, new { @placeholder = "Quantity", @class = "form-control" })</div><a href="#" class="remove_field">Remove</a></div>'); //add input box
after adding above code, when I click AddMore button, it reloads the page.
jquery..Html helpersare used on server side which actually converts your helpers to required html elements before sending response to client browser... So its quite not possible usingjquery. I would suggest rather to use apartialviewwhich contains the above controls, passing the list ofmodeland generating as much as control you want and load it using$.loadnameattribute which could never bind to your model when you submit (and duplicateidattributes which is invalid html). Refer the answers here and here for some options for dynamically adding and removing collection items.