1

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.

3
  • 1
    you will have to set its selected property... so value: productValue, text: productName, selected: true, also have to make it a multiselect Commented Aug 20, 2014 at 3:59
  • something like jsfiddle.net/arunpjohny/b8vwyjf2/1 Commented Aug 20, 2014 at 4:01
  • when you submit a form(or serialize form data) only selected values of the select element are sent Commented Aug 20, 2014 at 4:02

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

+1 , this is more cleaner approach to change DOM content rather string manipulation ..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.