Unable to access serialized select2 value in asp.net mvc controller

I'm facing a challenge with serializing and passing multiple controls inside a div to a controller via AJAX in my view. One of the fields, SchoolType, is a select2 multi-select dropdown.

Model :

public class SchoolModel
{
     public string StudentName{ get; set; }
     public List<string> SchoolType{ get; set; }
     public List<SelectListItem> SchoolTypeList{ get; set; }
}

View :

<div id="divSchool">
    <div class="row">
        <div class="col-md-12">
            <div class="col-md-6">
                <div class="form-group">
                    <label asp-for="SchoolType" class="col-md-3 control-label">School Type</label>
                    <div class="col-md-9">
                        <select asp-for="SchoolType" asp-items="Model.SchoolTypeList" class="form-control medium"></select>
                    </div>
                </div>
            </div>
            <div class="col-md-6">
                <div class="form-group">
                    <label asp-for="StudentName" class="col-md-3 control-label">Student Name</label>
                    <div class="col-md-9">
                        <input asp-for="StudentName" class="form-control" />
                    </div>
                </div>
            </div>
        </div>
    </div>       
</div>

Controller:

[HttpPost]
public ActionResult Index(SchoolModel model)
{
}

My JS Code:

$('#SchoolType').select2({
    placeholder: "Filter by school"
}

$("document").on("click", ".btnCheck", function () {
var model = $('#divSchool').find('select, textarea,input').serialize();

$.ajax({
        url: "/Student/Index",
        type: 'POST',
        data: { model: model },
        cache: true,
        async: true,
    }).done(function (result) {

    }).fail(function (error) {

    })
});

However, when serialized, the values appear like this:

model = "StudentName=Test&SchoolType=1b&SchoolType=26a"

The issue is that while the StudentName value is correct, the SchoolType value appears as null on the server side in the controller. How can I resolve this?

Possible issue: The SchoolType is a list of strings which might be causing it not to map correctly.

EDIT 1: I attempted changing the div into a form but encountered the same problem.

EDIT 2: A solution was found in PHP by modifying the select name. This answer provides an example.

Answer №1

Uncertain about manipulating the serialization part, but manually obtaining the desired structure is possible.

To serialize other controls similar to what you are doing with serialize() and assigning it to model, handle Select2 in this manner and incorporate it into the model.

model = {};
$(".select2").each(function () {
    var selectedValue = $(this).val();
    if (selectedValue != null) {
        model[this.name] = selectedValue;
    }
}); 

This technique will provide the necessary structure.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Save the JSON response from JavaScript to a different file extension in a visually appealing layout

I've created a script to generate both the CSR and private key. The response displayed in the <textarea> is well-formatted with newline characters (assuming familiarity with the correct CSR/Private key format). However, I'm encountering a ...

React Object is throwing an error - not a function

I need assistance resolving this issue. The error Object(...) is not a function keeps appearing in my code. Here is the snippet of code that seems to be causing the problem: It centers around the declaration of const useStyles = makeStyles(() => ({. ...

Instantiating a Google Cloud Function with a Real-Time Database Trigger Path

Looking for advice on Google Cloud functions triggered by RTDB - specifically, how to access the trigger path of an existing function. I'm encountering an issue when copying functions for different environments (dev vs. production) as the trigger path ...

Exploring Sprite Range with Raycasting in Three.js

I am working on a 3D scene using three.js and adding sprites, but I want to accurately determine the distance between the camera and a sprite when I click on the screen. To achieve this, I am utilizing a Raycaster. However, when clicking on the sprite, th ...

Adjusting the Size of an HTML Slideshow

While designing a homepage for my band, I encountered an issue when trying to integrate a slideshow element from an external source. The size of the slideshow is fixed at 600 x 300px and cannot be adjusted. Additionally, I found it challenging to position ...

Tips for preventing keys from being stored in a clear text file

Looking for a secure way to encrypt data in your Node.js and MySQL application? Concerned about avoiding storing plain keys in a file that could be easily accessed by unauthorized users? Encrypting data using AES_ENCRYPT(text, key) may not seem secure en ...

The challenge of Webpack errors arising from sharing a project between two different machines

My project is saved in a Google Drive folder and runs smoothly on one of my machines. However, when I try to compile the code on another machine, I encounter multiple errors all related to loading images. The error message below is just one example (others ...

Grouping geoJSON data on Mapbox / Leaflet

I am currently in the process of setting up a clustered map on mapbox, similar to the example shown here: At the moment, my point data is being extracted from MYSQL and then converted into GeoJson using GeoPHP. You can view the current map setup here. I ...

Issues arising from the event target

What is the reason behind this code functioning successfully only when the alert function is called? The color changes after closing the alert box, but if the line with the alert command is commented out, nothing happens. function setLinkColor(el) ...

"How to automatically populate an input field with a value when the page loads in an

I need assistance with setting the input value to 1 when the page is loaded, but for some reason, it remains empty. Can someone help me troubleshoot this issue? <tr *ngFor="let item of cartItems; let i=index"> <td class="cart_pr ...

Node.js is receiving an empty body from Postman when using form-data in the request

Even though I've searched extensively, I still have not found a solution to my specific issue despite it being asked before. const express = require("express"); require("dotenv").config({ path: ".env", }); const PORT = ...

What is the best way to navigate through a webpage to find a specific folder and show its contents on the page?

My goal is to design a webpage where users can browse their computer for a specific folder, select it, and have its content displayed on the webpage. I am fairly new to creating pages, but I want to develop a platform where you can easily find and view f ...

Having difficulties retrieving JSON data

I'm encountering an issue while trying to retrieve my JSON data using an AJAX request. JSON { "Ongoing": [ {"name": "meh"}, {"name": "hem"} ], "Completed": [ {"name": "kfg"}, {"name": "dkfgd"} ] } ...

Looking to implement a star rating feature in Vue.js 2?

My perspective is as follows : <div class="col-md-8"> ... <star-rating :value="3"></star-rating> ... </div> This is how my star-rating component looks like : <template> <span class="rating"> &l ...

JavaScript function: Reduce array if total string length exceeds specified value using a loop

I am currently working on a function to shorten a text if it exceeds a certain length. For example, calling shorten_text_easy(text, 30) should output "We believe. In the future". The initial loop is functioning correctly and showing the total l ...

Unable to transfer information from Angular.js to Node.js

I am currently developing a MEAN stack application that combines AngularJS and Node.js. Here is a snippet of my AngularJS code: app.js: var app = angular.module('crudApp', ['ngRoute']); app.config(['$routeProvider' ...

Obtain the count of unique key-value pairs represented in an object

I received this response from the server: https://i.stack.imgur.com/TvpTP.png My goal is to obtain the unique key along with its occurrence count in the following format: 0:{"name":"physics 1","count":2} 1:{"name":"chem 1","count":6} I have already rev ...

Issues with form rendering in a Vue.js component

I have recently started learning vue.js and I'm trying to create a basic form using the materializecss framework within a component. The form requires this jQuery snippet to function: $(document).ready(function() { M.updateTextFields(); }); ...

Ways to attach JQuery UI Sortable widget to html content fetched through Ajax requests?

Here's a straightforward question for you. Take a look at my JavaScript/jQuery code snippet below: $('body .combo-table').sortable({ handle: '.grabber', opacity: 0.9, axis: 'y', start: function (e, ui) { ...

Typescript's way of mocking fetch for testing purposes

I have a query regarding the following code snippet: import useCountry from './useCountry'; import { renderHook } from '@testing-library/react-hooks'; import { enableFetchMocks } from 'jest-fetch-mock'; enableFetchMocks(); i ...