Issue
I try to send an ajax request to my rest controller to edit an object user. One of the fields of it is a list of roles. Each role has Id and name, but when I fill the form I put this option in a select field as a text of its name. Here is the fragment:
$.ajax({
url: '/api/roles/',
method: 'get',
dataType: 'json',
contentType: "application/json",
success: function (result) {
$('#roles').empty();
$.each(result, function (k, v) {
var option = new Option(v.name, v.name);
$("#roles").append(option);
});
}
})
When I send the form values the list of roles goes as a list of strings, so the rest controller makes an object without the id field. What is the best way to fix it? I send it like this:
$.ajax({
url: '/api/users',
async: true,
// dataType: 'json',
contentType: "application/json",
type: "PUT",
data:
JSON.stringify( {
id : jQuery('#id').val(),
username: jQuery('#username').val(),
password: jQuery('#password').val(),
roles : jQuery('#roles').val()
})
})
Solution
Your ajax call to fill the select list
var option = new Option(v.name, v.name);
$("#roles").append(option);
creates an option element in HTML like
<option value="name">name</option>
The data you send with your second ajax call includes the value attribute of the selected option element. If you need the id of the role for your "/api/users" controller, you simply need to set the id in the first place.
So just initiate the option elements in a way like
var option = new Option(v.name, v.id);
$("#roles").append(option);
and you will get
<option value="id">name</option>
This way you will get the id of the selected role for the /api/users script when calling jQuery('#roles').val().
Answered By - karstenmtr