Model Binding is Failing when I pass JSON via $.get()
-
24-09-2019 - |
Question
This question is related to the this.
I'm using the following to extract the attributes & values from the select elements on my page:
var valuesArray = $("select").map(function()
{
return $.getAttributes($(this).find(":selected"));
});
var arr = new Array();
$.each(valuesArray, function()
{
arr.push($(this)[0]); // this filters out things like 'length'
});
basically, after I get an array of the objects representing the attributes of my select boxes, I want to convert that to a data string that I can pass to the server
// get data string for server
var data = $.toJSON(arr);
The JSON returned is:
[{"siteId":"2"},{"filterId":"2","factSheetPanelId":"2"}]
and I pass it to the server like so:
$.get(url, data, function(result)
{
// do stuff
}, "html");
The code on the server is but it's not picking up the values & Model Binding is failing
public PartialViewResult PanelList(FactsheetPanel panel, Site site)
{
// panel.FactsheetPanelId == 0. I would expect it to be 2
// same for site.SiteId..
}
Can anyone see anyting obviously wrong with this?
Solution
Don't pass JSON. jQuery will simply pass that to the server, which won't know what to do with it unless you write a JSON data binder.
Instead, pass a JavaScript object. jQuery will serialize that into query string parameters, which work correctly. E.g.:
var data = {
panel: { filterId: "2", factSheetPanelId: "2" },
site: { siteId: "2" }
};
OTHER TIPS
That looks wrong. It would have helped if you also posted your FactsheetPanel
and Site
classes but anyway, as far as I understand, here's how your JSON should be after getting the values from your HTML elements and processing them.
{"site.siteId":"2", "panel.filterId":"2","panel.factSheetPanelId":"2"}