When a form contains no selected items, it creates me a table with one ite that is 0, how to remove it elegantly? where?
JS :
$(document).on('click', '#submitButton', function () {
showLoader();
$.ajax({
url: "@Url.Action("Search", "Home")",
cache: false,
type: "POST",
dataType: "html",
traditional: true,
data: { secteurs: $("#secteursDiffusion").val(), auditeurs: $("#auditeursDiffusion").val(), audites: $("#auditesDiffusion").val(), services: $("#servicesDiffusion").val() },
success: function (result) {
$("#resultPlaceholder").html(result);
}
});
});
At this point, when I evaluate in console $("#secteursDiffusion").val() for instance, I can see items that were selected in $("#secteursDiffusion"), OK (result:["676"]) ! And when I evaluate $("#auditesDiffusion").val() in console, this is null (result:null), so all is OK.
In the controller:
public ActionResult Search(int[] secteurs, int[] auditeurs, int[] audites, int[] services)
{ ... }
when I breakpoint in the controller, I received audites (that were evaluated in console as null) with one item that is 0, why? And how remve it elegantly?
Thanks in advance
EDIT:
HTML Code of one input:
<select data-placeholder="Ajoutez un ou plusieurs secteurs" id="secteursDiffusion" multiple="multiple" name="secteursDiffusion">
<option value="992379">item55</option>
<option value="993147">item56</option>
<option value="996096">item57</option>
<option value="33033095">item58</option>
</select>
EDIT2: with int?[] Same problem:
Although the value is null
you are still passing some value for audites
. As it is not an array, MVC thinks you are passing an int
value and so sets it to its default value - 0
(as Stephen pointed out, this is the behaviour of the DefaultModelBinder
).
You need to ensure an array is passed, so if it is null
, send []
instead - note that audites
then becomes null
in the controller action, rather than an empty array, but that makes more sense than [0]
:
$(document).on('click', '#submitButton', function () {
showLoader();
$.ajax({
url: "@Url.Action("Search", "Home")",
cache: false,
type: "POST",
dataType: "html",
traditional: true,
data: {
secteurs: $("#secteursDiffusion").val() || [],
auditeurs: $("#auditeursDiffusion").val() || [],
audites: $("#auditesDiffusion").val() || [],
services: $("#servicesDiffusion").val() || []
},
success: function (result) {
$("#resultPlaceholder").html(result);
}
});
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.