Reputation: 13
I'm using ASP.NET MVC 4
Let's puttig this way, this is my Html:
<select id="cmbProducts" name="Products" class="form-control">
<option value="1">Product1</option>
<option value="2">Product2</option>
<option value="3">Product3</option>
</select>
<button id="cmdAddProduct" type="button">Add selected product</button>
<select id="cmbAddedProducts" name="AddedProducts" size="8" class="form-control">
<!-- These options are added dinamically on click via jQuery -->
</select>
And this is my jQuery function
$(function () {
$("#cmdAddProduct").click(function (e) {
var productName = $('#cmbProducts :selected').text();
var productValue = $('#cmbProducts :selected').val();
var exists = false;
$("#cmbAddedProducts > option").each(function () {
if (this.text == productName) {
exists = true;
}
});
if (!exists) {
$('#cmbAddedProducts').append($('<option>', {
value: productValue,
text: productName
}));
}
});
It works perfect adding elements to my list. My problem is I'm trying to get the options array which were added dinamically on 'cmbAddedProducts' (these are being added using .append on my function).
On my controller, I'm using an ActionResult to retrieve the options on the <select>
public ActionResult AEventos(FormCollection form) {
string[] AddedProducts = Request.Form.GetValues("AddedProducts");
}
But it only retrieves the <option>
's that I added directly on html code, not the added dynamically using jQuery on my buttons click.
I think this is related to the DOM not updating but I've been searching for help without success, and still have no idea about how to solve this.
Upvotes: 1
Views: 572
Reputation: 6766
Update your javascript to
$('#cmbAddedProducts').append($('<option>', {
value: productValue,
text: productName,
selected: true
}));
so that option you add will get selected in your DOM and thus this will be getting accessed from your controller.
Upvotes: 3