When I send data from my view to web api controller my ID fields are always got null in controller, below is my code
$scope.Create_Click = function (CategoryselectedItemvalue, SupplierSelectedItemvalue, Product_Name, Quantity_PerUnit, Reorder_Level, Unit_Price, Units_InStock, Units_OnOrder) {
var CategoryID = parseInt(CategoryselectedItemvalue);
var SupplierID = parseInt(SupplierSelectedItemvalue);
var ProductName;
var QuantityPerUnit;
var ReorderLevel;
var UnitPrice;
var UnitsInStock;
var UnitsOnOrder;
Product = {
CategoryID: CategoryID,
SupplierID: SupplierID,
ProductName: Product_Name,
QuantityPerUnit: Quantity_PerUnit,
ReorderLevel: Reorder_Level,
UnitPrice: Unit_Price,
UnitsInStock: Units_InStock,
UnitsOnOrder: Units_OnOrder
};
$http({
method: 'POST',
url: '/api/Products/PostProduct',
data: JSON.stringify($scope.Product),
headers: { 'Content-Type': 'application/JSON' }
}).
success(function (data) {
alert("Record Added");
}).
error(function (msg) {
alert(msg);
});
};
});
Below is my controller method (here when I recieved data CategoryID and SupplierID is always null)
[ActionName("PostProduct")]
public IHttpActionResult PostProduct(Product product)
{
Product pro = new Product();
pro.CategoryID = product.CategoryID;
pro.SupplierID = product.SupplierID;
pro.ProductName = product.ProductName;
pro.QuantityPerUnit = product.QuantityPerUnit;
pro.ReorderLevel = product.ReorderLevel;
pro.UnitPrice = product.UnitPrice;
pro.UnitsInStock = product.UnitsInStock;
pro.UnitsOnOrder = product.UnitsOnOrder;
if (repo.AddNewProduct(pro))
{
return Ok("Product Added");
}
else
{
return Ok("Error");
}
}
Since your header is 'application/json', I don't think there is any need of using JSON.stringify which basically converts json to a string and therefore, you cannot access your keys.
Just send your object as it is in JSON format.
While stringifying data it should be in JSON format, where its key would be product(action parameter name)
data: JSON.stringify({product : $scope.Product}),
Or you don't need to stringify your data if you are using Web.API, you just only need to use [FromBody] attribute before you Product parameter in action.
[ActionName("PostProduct")]
public IHttpActionResult PostProduct([FromBody] Product product)
{
//code is the same
}
Related
I'm trying to post a single object data to an MVC Controler using JQuery, Below are my codes.
//declare of type Object of GroupData
var GroupData = {};
//pass each data into the object
GroupData.groupName = $('#groupName').val();
GroupData.narration = $('#narration').val();
GroupData.investmentCode = $('#investmentCode').val();
GroupData.isNew = isNewItem;
//send to server
$.ajax({
url: "/Admin/SaveContributionInvestGroup",
type: "POST",
contentType: "application/json;charset=utf-8",
dataType: "json",
data: JSON.stringify({ GroupData: JSON.stringify(GroupData) }),
success: function (res) {
alertSuccess("Success", res.Message);
//hide modal
$('#product-options').modal('hide');
hide_waiting();
},
error: function (res) {
alertError("Error", res.Message);
}
});
Below is my controller.
[HttpPost]
public JsonResult SaveContributionInvestGroup(ContributionInvestmentGroup GroupData)
{
ClsResponse response = new ClsResponse();
ClsContributionInvestmentGroup clsClsContributionInvestmentGroup = new ClsContributionInvestmentGroup();
var userID = (int)Session["userID"];
var sessionID = (Session["sessionID"]).ToString();
if (contributionGroupData != null)
{
//get the data from the cient that was passed
ContributionInvestmentGroup objData = new ContributionInvestmentGroup()
{
contributionInvestmentGroupID = 0,
groupName = GroupData.groupName,
narration = GroupData.narration,
investmentCode = GroupData.investmentCode,
isNew = GroupData.isNew
};
response = clsClsContributionInvestmentGroup.initiateNewContributionInvestmentGroup(sessionID, objData);
}
else
{
response.IsException = true;
response.IsSucess = false;
response.Message = "A system exception occurred kindly contact your Administrator.";
}
return Json(new
{
response.IsSucess,
response.Message
});
}
The issue is, the data is not been posted to the controller, the controller receives a null object.
Kindly assist, would really appreciate your effort, thanks.
Try Like this:
//send to server
$.ajax({
type: "POST",
url: "/Admin/SaveContributionInvestGroup",
dataType: "json",
data: GroupData,
success: function (res) {
alertSuccess("Success", res.Message);
//hide modal
$('#product-options').modal('hide');
hide_waiting();
},
error: function (res) {
alertError("Error", res.Message);
}
});
in your controller your dont have custom binding to bind JSON to your model thats why you get null in you parameter.
instead just post it as query, try simply changes your ajax option like so:
{
...
contentType: "application/x-www-form-urlencoded", //default:
...,
data: $.param(GroupData),
...
}
and perhaps property names are case sensitive so you will need to change your javascript model's name
I read many articles describing this and I tried to use the same mechanism but still it does not work for me.
So, I want to send the object from javascript to my controller.Here is the snippet I tried but error 400(Bad request).
My bean is as follow : (StudentAnswers.java)
public class StudentAnswers {
private Integer testId;
private Integer studentId;
private String[] questionIds;
private String[] answerIds;
..
//all get and set method to access this
}
My javascript file having ajax call is :
function submitTest()
{
var test_id = 1;
var student_id = 1;
var q = [];
q[0] = "question 1";
q[1] = "question 2";
var a = [];
a[0] = "answer 1";
a[1] = "answer 2";
var studentAnswers = {
"testId": test_id,
"studentId": student_id,
"questionIds": q,
"answerIds" : a
};
$.ajax({
type : "POST",
url : "submitTest",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
data : studentAnswers,
success : function(response) {
alert('test submitted');
},
error : function(e) {
alert('Error: ' + e);
}
});
Finally, my controller function is :
#RequestMapping(value={"submitTest"},method = RequestMethod.POST)
public ModelAndView submitTest(#RequestBody StudentAnswers studentAnswers)
{
...
return new ModelAndView("student/testBegin");
}
Try to stringify post data like this:
data : JSON.stringify(studentAnswers)
var studentAnswers = new Object();
studentAnswers.testId = "11";
studentAnswers.studentId = "12345";
studentAnswers.questionIds = "secret";
studentAnswers.answerIds ="111";
$.ajax({
url: urlSelected,
type: "POST",
dataType: "json",
data: JSON.stringify(studentAnswers),
contentType: "application/json",
mimeType: "application/json",
success: function (result) {
if (result.success) {
alert(result.message);
} else {
alert(result.message)
}
},
error:function(error) {
alert(error.message);
}
});
Thank you guys for the help.
I tried using JSON.stringify to send the data from AJAX to Controller and it did not work.
JSON.stringify(studentAnswers)
However, when I took a look at the data that I am sending and compare with the type of data expected, I found out that there was a type mismatch.
So, I changed my javascript Object to be identical to my bean. So, following is my object and bean which works fine.
JavaScript Object :
var studentAnswers = new Object();
studentAnswers.testId = 1;
studentAnswers.studentId = 1;
studentAnswers.questionIds = new Array();
studentAnswers.questionIds[0] = "12345";
studentAnswers.answerIds =new Array();
studentAnswers.answerIds[0] = "12345";
Bean :
public class StudentAnswers {
private Integer testId;
private Integer studentId;
private String[] questionIds;
private String[] answerIds;
..
//all get and set method to access this
}
Final AJAX call looks like this :
$.ajax({
type : "POST",
url : "submitTest",
dataType: "json",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
data : JSON.stringify(studentAnswers),
success : function(response) {
alert('test submitted');
},
error : function(e) {
alert(e.message);
}
});
Controller Function:
#RequestMapping(value={"submitTest"},method = RequestMethod.POST)
public ModelAndView submitTest(#RequestBody StudentAnswers studentAnswers)
{
System.out.println(studentAnswers.toString());
return new ModelAndView("student/testBegin");
}
I have a form in my view which has only one textarea input initially and user can add more textarea inputs if he wants with jquery. My problem is related to second case. After submitting the form i am getting an array of objects in console but when i am passing this array to mvc action in my controller it is coming to be null.
I have tried these solution but did not succeed:
Send array of Objects to MVC Controller
POST a list of objects to MVC 5 Controller
here is my code:-
jquery code:
$('body').on('submit', '#addTextForm', function () {
console.log($(this));
var frmData = $(this).serializeArray();
console.log(frmData);
$.ajax({
type: 'post',
url: '/Dashboard/UploadText',
contentType: 'application/json',
data: JSON.stringify({ obj: frmData }),
success: function (data) {
console.log(data);
},
error: function (data) {
console.log(data);
}
});
return false;
});
MVC action:
[HttpPost]
public string UploadText(SliderTextList obj)
{
return "success";
}
my object class:
public class SliderText
{
[JsonProperty("Id")]
public int Id { get; set; }
[JsonProperty("SlideName")]
public string SlideName { get; set; }
[JsonProperty("Content")]
public string Content { get; set; }
}
public class SliderTextList
{
public List<SliderText> AllTexts { get; set; }
}
I have to store the Content in json file with Id and SlideName, so i think i have to pass a list object in mvc action Uploadtext which is coming out to be null always. Please help.
$(document).ready(function(){
$('body').on('submit', '#addTextForm', function () {
var listData=[];
var oInputs = new Array();
oInputs = document.getElementsByTag('input' );
var k=1;
for ( i = 0; i < oInputs.length; i++ )
{
if ( oInputs[i].type == 'textarea' )
{
var obj=new Object();
obj.Id=k;
obj.SlideName=oInputs[i].Name;
obj.Content=oInputs[i].Value;
K=parseInt(k)+1;
listData.push(obj);
}
}
$.ajax({
type: 'post',
url: '/Dashboard/UploadText',
contentType: 'application/json',
data: JSON.stringify(listData),
success: function (data) {
console.log(data);
},
error: function (data) {
console.log(data);
}
});
return false;
});
});
Since the sever side expects a string as argument obj as a query string I think this is what you need.
data: {
obj: JSON.stringify(frmData)
},
as an alternative using as Stephen suggested on the comments
data: {
obj: $('#addTextForm').serialize()
},
Thanks for all your input, but now I have more or less a similar problem, I have the data that needs to be stored in sql-server database, when I try to post it the data does not get written. Is my code structure correct?
self.CurrentDowntimeEvent = {
method: 'POST'
, url: 'someurl/test'
, data: {
DepartmentId: cookie
, CategoryId: -1
, Comment: ""
, DowntimeStart: "2014-07-07T10:00:00"
, DowntimeEnd: null
}
, headers: {'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8'}
}).success(function (data) {
console.log(data);
}).error(function (data) {
});
$http is a service which should be injected into the controller, so you shouldn't need self. to reference it:
self.RecordsSave = function () {
for (var i = 0; i < self.Employees.length; i++) {
var employee = self.Employees[i];
var params = {
CompanyNumber: employee.ClockNumber,
Department: employee.DepartmentID,
Present: employee.Present,
Reason: employee.AbsentCode
};
$http.post(SAVE_EMPLOYEERECORDS, {
params: params
}).success(function (data) {
alert("testing");
});
}
};
I have asp.net application where need to implement autocomplete, I try to load list of names from server side and then deserealize it in js code, but have an 500 error, can anybody help me?
Unknown web method GetListofCompanies.
Parameter name: methodName
Code:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string GetListofCompanies(string name) {
var companies = _companyRepo.GetAll().Select(x => x.Name).ToList();
// Create a JSON object to create the response in the format needed.
JavaScriptSerializer oJss = new JavaScriptSerializer();
// Create the JSON response.
String strResponse = oJss.Serialize(companies);
return strResponse;
}
JS:
var name = "";
$.ajax({
url: "Company.aspx/GetListofCompanies",
type: "post",
data: { name: name },
dataType: "json",
contentType: 'application/json',
success: function (data) {
// Get the data.
var responseArray = JSON.parse(data.d);
$("#txtName").autocomplete({
source: responseArray
});
}
});
// Namespaces.
using System.Web.Services;
using System.Web.Script.Serialization;
[WebMethod]
public static string GetListofCompanies(string name)
{
List<string> companies = new List<string>();
companies.Add("Company1");
companies.Add("Company2");
companies.Add("Company3");
companies.Add("Company4");
companies.Add("Company5");
// Create a JSON object to create the response in the format needed.
JavaScriptSerializer oJss = new JavaScriptSerializer();
// Create the JSON response.
String strResponse = oJss.Serialize(companies);
return strResponse;
}
// JS
function request() {
var name = "";
var data = { name: name };
$.ajax({
url: "Default.aspx/GetListofCompanies",
type: "POST",
contentType: 'application/json',
data: JSON.stringify(data)
}).success(function (data) {
// do your stuff here
})
.fail(function (e) {
alert("Error");
});
}