0

I have a simple form containing two fields When i submit the form using a jQuery ajax function the server only receive the first field data but not the second field data ?

First Field: Dropdownlist (single value selection.)

Second Field: Dropdownlist (Multi value selection.)

Here is my Code:

Form:

<form id="formId">
    <div class="form-group">
        <label>Customer</label>
        @Html.DropDownListFor(m => m.Customers, new SelectList(Model.Customers, "id", "name"), "Select Customer", new { @class = "form-control", id = "customer_Id" })
    </div>

    <div class="form-group">
        <label>Book</label>
        @Html.DropDownListFor(m => m.Books, new MultiSelectList(Model.Books, "id", "name"), "Select Books", new { multiple = "true", @class = "form-control", id = "Book_Ids" })
    </div>
    <button type="submit" class="btn btn-primary">Submit</button>
</form>

jQuery Code:

@section scripts{
    @Scripts.Render("~/bundles/jquery");
    <script type="text/javascript">
        jQuery(document).ready(function () {

            var viewModel = {
                Customers: "",
                Books: []
            };
            
            // Loading data to viewModel.
            $("#btn_Test").on("click", function () {
                var selectedCustomerId = $("#customer_Id").val();
                var selectedBooksIds = $("#Books_Ids").val();
                viewModel.Customers = selectedCustomerId;
                for (var i = 0; i < selectedBooksIds .length; i++) {
                    viewModel.Books.push(parseInt(selectedBooksIds[i]));//Added parseInt to parse value to int
                }
            });

            // Submit Form.
            $("#formId").submit(function (e) {
                e.preventDefault();
                jQuery.ajax({
                    url: "/RecordCustomerAndBooksIds/Create",
                    method: "post",
                    data: viewModel,
                    success: function () { alert("Done."); },
                    fail: function () { alert("Failed."); }
                });
            })

        });
    </script>
}

ViewModel: (When User click submitting the form the target viewModel will recieve the appropriate Id's.)

public class CustomerIdAndBooksIdsViewModel
{
   public int Customers { get; set; }
   public List<int> Books { get; set; }
}

Action Method:

When submitting form: the CustomerIdAndBooksIdsViewModel Object receiving only Customers(customer Id) and the Books(books Ids) is null ?

public ActionResult Create(CustomerIdAndBooksIdsViewModel ids) //
{
   //...
}

How to Solve it ?I Shall be very thanksful.

4
  • Is this a typo in the question? viewModel.Books*s*.push(selectedBooksIds[i]); Commented Jan 24, 2019 at 12:19
  • @Peter Sorry for it..it was happen during editing question... Commented Jan 24, 2019 at 12:21
  • have you tried using an array of int in the viewmodel instead of a list? (int[] Books {get; set;}) the binding on a mvc can be very picky when it comes to what it will bind. Commented Jan 24, 2019 at 14:30
  • yes....i tried that as well....same as the case.. Commented Jan 24, 2019 at 16:45

2 Answers 2

1

What is happening here is in viewModel.Books, you are pushing as string but on controller's Action it is expecting an list of int.

Try parsing the values to INT before posting the values, something like this:

for (var i = 0; i < selectedBooksIds.length; i++) 
{
   //Added parseInt to parse value to int
   viewModel.Books.push(parseInt(selectedBooksIds[i]));
}
Sign up to request clarification or add additional context in comments.

1 Comment

ViewModel still receives a null value for Books.
0

try using select2

<script>
$(document).ready(function () {

    //The url we will send our get request to
    var booksUrl = '@Url.Action("GetBooks", "Home")';
    $('#books').select2(
    {
        placeholder: 'Select Books',
        multiple: true,
        ajax: {
            //The url of the json service
            url: booksUrl,
            dataType: 'jsonp'
            }
    }
  });
 </script>



<form id="formId">
<div class="form-group">
    <label>Customer</label>
    @Html.DropDownListFor(m => m.Customers, new SelectList(Model.Customers, "id", "name"), "Select Customer", new { @class = "form-control", id = "customer_Id" })
</div>

<div class="form-group">
    <label>Book</label>
    @Html.TextBoxFor(m => m.Books, new { id = "Book_Ids" }) 
</div>
<button type="submit" class="btn btn-primary">Submit</button>

2 Comments

In my case ... in the second dropdownlist i am retreiving All Book list from a viewModel....in your case how to do that ?
The official select2 site is here: ivaynberg.github.io/select2 You should request the list from a method that will give you the list of objects. Request from inside select2 using ajax option. In your back end create the method called. I have updated the answer for you

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.