Reputation: 604
I am trying to make an ajax sending data in JSON from a partial view. I get a System.ArgumentException: Invalid JSON primitive: undefined. When I evaluate the object in a browser data contains an int and two strings. Can anyone tell me what I am doing wrong?
Partial View
@model FTD.Models.FTDAccountExtended
@using (Html.BeginForm()) {
<fieldset>
<legend>Update Policy Number</legend>
@Html.HiddenFor(m => m.account.ftd_accountsid)
@Html.HiddenFor(m => m.OldPolicyNumber)
@Html.TextBoxFor(m => m.account.ftd_policyno)
<input type="button" value="update" id="update" />
</fieldset>
}
<script type="text/javascript">
$(document).ready(function () {
$("#update").click(function () {
var myUrl = '@Url.Content("~/")' + '/Maintenance/UpdatePolicyNumber';
var data = [{ 'ClientNumber': parseInt($("#account_ftd_accountsid").val()), 'OldPolicyNumber': $("#OldPolicyNumber").val(), 'NewPolicyNumber': $("#account_ftd_policyno").val()}];
$.ajax({
url: myUrl,
type: 'POST',
data: data,
contentType: 'application/json; charset=utf-8',
success: function (data) {
alert(data.message);
},
error: function (errMsg) {
alert("Error", errMsg);
}
});
});
});
The controller method is
public ActionResult UpdatePolicyNumber(int ClientNumber, string OldPolicyNumber, string NewPolicyNumber)
{
var message = string.Format("UpdatePolicyNumber CN:{0} OP:{1} NP:{2}", ClientNumber, OldPolicyNumber, NewPolicyNumber);
if (_log.IsDebugEnabled)
_log.Debug(message);
if (!string.IsNullOrEmpty(NewPolicyNumber) && ClientNumber > 0)
{
_entities = new CloseFTD_Entities();
_entities.UpdatePolicyNumber(ClientNumber, OldPolicyNumber, NewPolicyNumber, User.Identity.Name);
}
return Json
(
new
{
message = message
},
JsonRequestBehavior.AllowGet
);
}
Upvotes: 1
Views: 1360
Reputation: 398
I would just try posting the the data as a java script object (as Marc mentioned above) and remove the content type attribute.
Upvotes: 1
Reputation: 6771
Your problem is here
var data = [{ 'ClientNumber': parseInt($("#account_ftd_accountsid").val()), 'OldPolicyNumber': $("#OldPolicyNumber").val(), 'NewPolicyNumber': $("#account_ftd_policyno").val()}];
You are building an array - but your controller excepts the direct values, so just remove the []
brackets:
var data = { 'ClientNumber': parseInt($("#account_ftd_accountsid").val()), 'OldPolicyNumber': $("#OldPolicyNumber").val(), 'NewPolicyNumber': $("#account_ftd_policyno").val()};
That should work.
Upvotes: 1
Reputation: 2097
success: function (data) {
alert(data.success);
},
shouldn't this be
success: function (data) {
alert(data.message);
},
Upvotes: 1