Trying to create AJAX request manually. On clientside I have something like this:
function saveBatterySpecs(id) {
var url = '@Url.Action("SaveBatterySpecs", "Catalog")';
$.ajax({
type: "post",
url: url,
data: {
art: $("#art" + id).val(),
brand: $("#brand" + id).val(),
name: $("#name" + id).val(),
country: $("#country" + id).val(),
volt: $("#volt" + id).val(),
cap: $("#cap" + id).val(),
sp: $("#sp" + id).val(),
powc: $("#powc" + id).val(),
term: $("#term" + id).val(),
mount: $("#mount" + id).val(),
adds: $("#adds" + id).val(),
length: $("#length" + id).val(),
width: $("#width" + id).val(),
height: $("#height" + id).val(),
guar: $("#guar" + id).val()
},
dataType: 'text', //or json, no difference
success: hideEditForm(id)
});
and on server a simple
public ActionResult SaveBatterySpecs(string batteryData)
{
if (Request.IsAjaxRequest())
{
Debug.WriteLine(batteryData);
return PartialView("~/Views/Shared/EmptyView.cshtml");
}
else
return null;
}
Breakpoint on controller works, all Ok, browser debugger shows normal request with data. But I can't handle that - batteryData is allways null. What I'm doing wrong? Solution with forms useless because we avoiding them and can't currently use. I can switch type from text to json, but this doesn't help.
I think its not working because you pass the wrong argument to controller.
try to pass object instead string.
public class BatteryInfo
{
public long brand {get;set;}
public int height {get;set;}
etc.
}
then recive it in controller
ublic ActionResult SaveBatterySpecs(BatteryInfo battery)
and why not serialize the form instead of collecting all data from form elements? look here for details
I'd suggest what maxs87 brings up, where you post the actual object instead of a string representing the data.
But if you really wanted to accept only a string, you still need the matching variable name:
This will post one parameter called batteryData
, whose value is a JSON string representing all that data. On the controller, your batteryData
variable will be populated with a JSON string which you can manually deserialize.
data: {
batteryData: JSON.stringify({
art: $("#art" + id).val(),
brand: $("#brand" + id).val(),
name: $("#name" + id).val(),
})
},