Passing JSON array to MVC Controller Action not working - arrays

We want to pass a JSON array to an MVC Controller Action. The Action Takes a list of Cards as parameter. When we call the Action, the parameter is null.
This is the client-side code:
function PrintCards() {
var CardsArray = [];
CardsArray = GenerateArrayOfCards();
//CardsArray has the desired data
var errors = JsonResults('/Operator/PrintCards', 'Cards=' + CardsArray, 'Post');
if (errors != '') {
alert('Something went wrong!');
return false;
}
alert('Cards got Successfully assigned.');
}
And on the server-side we have the following Action
Public Function PrintCards(Cards As List(Of Card)) As JsonResult
Try
PrintAllCards(Cards)
Return Json(String.Empty, "application/json", UTF8Encoding.UTF8)
Catch ex As Exception
Return Json(New With {.error = "Something went wrong!"}, "application/json", UTF8Encoding.UTF8)
End Try
End Function
The problem is that in the Action, Cards is null while in the view (client-side) the array has data. Is there any convert or something missing?

Related

How to return data from web api controller using angularjs?

Hi I am developing one web api with angularjs application. I am doing file upload module. I am facing problem in returning object once file upload is finished.
Below is my api code to save file related data to database and if it is succsfull I am returning object.
NCT_FileUpload obj = new NCT_FileUpload();
obj.file_path = uploadPath;
obj.user_id =9;
entityObject.NCT_FileUpload.Add(obj);
int result = entityObject.SaveChanges();
if (result == 1)
{
return Request.CreateResponse<NCT_FileUpload>(HttpStatusCode.OK, obj);
}
else
{
return Request.CreateErrorResponse(HttpStatusCode.NotFound, "1");
}
This is my angularjs code.
$scope.uploadFiles = function () {
$scope.uploading = true;
uploadService.uploadFiles($scope)
// then() called when uploadFiles gets back
.then(function (data) {
// promise fulfilled
$scope.uploading = false;
if (data === '') {
alert("Done!!!")
$scope.formdata = new FormData();
$scope.data = [];
$scope.countFiles = '';
$scope.$apply;
} else {
alert("Shit, What happended up there!!! " + data);
}
}, function (error) {
$scope.uploading = false;
//Server Error
alert("Shit2, What happended up there!!! " + error);
}
);
};
Below is my service code in angularjs
if (typeof response.data === 'string') {
return response.data;
} else {
return $q.reject(response.data);
}
Here i want to check with object and not as string.
I am able to save data in server, If i put below code in api controller i am able to display done. But i am returning object so my data will not be empty. Currently my error function is executing. I want to handle object returned from api in success function. Is there any way to do this? Any help would be appreciated. Thank you.
return new HttpResponseMessage(HttpStatusCode.OK) ;
I think the problem here is the generic parameter. Change this:
return Request.CreateResponse<NCT_FileUpload>(HttpStatusCode.OK, obj);
To this:
return Request.CreateResponse(HttpStatusCode.OK, obj);

How to return data from Web Api controller?

Hi I am developing restfull web api application. After inserting data into database i want to return 0 for success,1 for error and data as unique id assigned to the user. I want to return above data in json format. My requirement is i have to send data to controller in json format and receive data in json format. I have following code and it is working but i want to ask few points here.
Below is my User_Creation controller code.
public result Post(Noor_Users users)
{
result obj = new result();
if (ModelState.IsValid)
{
entityObject.Noor_Users.Add(users);
int result = entityObject.SaveChanges();
if(result==1)
{
obj.success = 0;
obj.id = 5;
return obj;
}
else
{
obj.error = 1;
return obj;
}
}
else
{
obj.error = 1;
return obj;
}
}
}
My service.js file contains below code.
app.service("UserCreation", function ($http) {
this.saveSubscriber = function (sub) {
return $http({
method: 'post',
data: JSON.stringify(sub),
url: 'api/User_Creation',
contentType: "application/json"
});
}
});
This is my controller.js code.
app.controller('UserCreation', function ($scope, UserCreation) {
$scope.saveSubs = function () {
var sub = {
user_email: $scope.user_email,
user_password: $scope.user_password,
};
var saveSubs = UserCreation.saveSubscriber(sub);
saveSubs.then(function (data) {
alert(JSON.stringify(data.data));
}, function (error) {
console.log('Oops! Something went wrong while saving the data.')
})
};
});
I am expecting response in json format as below.
● status - 0 for success, 1 for failure.
● data
○ id - unique id assigned to the user
● error - error message if failed
This is working absolutelt fine. I have below line of code in webapiconfig.cs file
config.Formatters.JsonFormatter.SupportedMediaTypes
.Add(new System.Net.Http.Headers.MediaTypeHeaderValue("text/html"));
With this line of code always i can receive data in json format. But in angularjs success call i need to stringify recieved data. If all my data is returning in json then again why i should convert it to json? Also someone can tell me is above logic is a good practice to return data? Thank you.
Try the following steps:
Add this two line of code on top of your WebApiConfig.cs
public static void Register(HttpConfiguration config)
{
config.Formatters.Clear();
config.Formatters.Add(new JsonMediaTypeFormatter());
Edit you controller action with following one
public IHttpActionResult Post(Noor_Users users)
{
result obj = new result();
if (ModelState.IsValid)
{
entityObject.Noor_Users.Add(users);
int result = entityObject.SaveChanges();
if (result == 1)
{
obj.success = 0;
obj.id = 5;
}
else
{
obj.error = 1;
}
}
else
{
obj.error = 1;
}
return Ok(obj);
}

Getting status 500 when using angularjs $http to get data from server

I am working on an asp.net mvc application and I am using Entity Framework and AngularJS in it. I am using AngularJS's $http service to call an action method and retrieve data from the server. The correct data is retrieved from the server (I confirmed this by debugging), but somehow an error occurs after the action method returns the retrieved data and the error callback function is fired instead of the success callback function. And then I get a status 500 in the browser's console.
Here are the involved blocks of codes:
(From angularjs controller)
$http({
url: rootUrl + "User/GetUser",//'#Url.Action("GetUser","User")',
method: 'POST',
params: {
uname: $scope.username,
pword: $scope.pass
}
}).then(function (response) {
alert('success!');
$scope.user = response.data;
if ($scope.user.Fullname != undefined) {
$http({
url: rootUrl + "Session/Set",
method: "POST",
data: {
"key": "curr_user",
"value": JSON.stringify($scope.user)
}
});
window.location.href = rootUrl + 'Product/List/';
} else {
//invalid login
$("input[name='password']").select();
$("#validation-summary").html("Wrong email or password.");
$scope.invalidlogin = true;
$(btnLogin).removeClass('disabled');
$(btnLogin).text("Submit");
}
(From mvc controller)
[HttpPost]
public JsonResult GetUser(string uname, string pword)
{
JBManager manager = null;
using (SE_Context db = new SE_Context())
{
try
{
manager = db.Managers
.Include("Transactions.Items")
.Where(m => m.Username == uname && m.Password == pword)
.FirstOrDefault();
//At this point, manager has the desired data
return Json(manager, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
return null;
}
}
}
And here's a screenshot of the error in the browser:
Would really appreciate any help. Thanks!
UPDATE:
Everything was working fine before I used Entity Framework. (Just in case it has something to do with the issue)
I think your issue is nested objects.You can flatten object graphs that contain nested objects using DTOs (Data Transfer Objects).
You can just try simple example as like below.If it'll work then you need to extend it to work with your EF query.
public class MyDto
{
public string Name { get; set; }
}
[HttpPost]
public JsonResult GetUser(string uname, string pword)
{
JBManager manager = null;
using (SE_Context db = new SE_Context())
{
try
{
//construct the DTO here
manager = db.Managers.Select(a=> new MyDto(
{
Name = a.Name
})).FirstOrDefault(m => m.Username == uname && m.Password == pword);
return Json(manager, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
return null;
}
}
}
You can read more about DTOs here : Create Data Transfer Objects (DTOs)

Retrieving POSTED data from controller

I'm using angular js. I posted data to a controller in vb.net from a JS file. How can I retrieve the data in the vb controller?.
Below is my app.factory method.
UpdateServiceData: function (p1, p2) {
var data = $.param({
fName: "John",
lName: "Smith"
});
var config = {
headers: {
'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'
}
}
$http({
method: "post",
url: '../api/Service/UpdateSvcData',
data,
config,
params: {
'P1': p1,
'P2': p2
}
}
});
}
UpdateSvcData is a method inside the controller ServiceController.vb
I just need to retrieve the posted values inside ServiceController.vb
i.e., I need to get fName and lName.
In short, I'm posting values from a JS file. I need to retrieve it at the ServiceController.vb using vb.net
I tried Request.QueryString("fName"), Request.Form["fName"] etc. But these are not giving the results.
Thanks
Public Function UpdateServiceData(<FromUri()> request As ServiceEntities) As HttpResponseMessage
Dim success As Boolean = True
Dim response As HttpResponseMessage
Try
Dim dataAccess As DB.DataAccessBase = DB.DataAccessBase.GetInstance(DataAcessTypes.Service)
request.MethodName = "UpdateServiceData"
Dim sJSON As String = dataAccess.Select(Of ServiceEntities)(request)
response = Me.Request.CreateResponse(HttpStatusCode.OK)
response.Content = New StringContent(sJSON, Encoding.UTF8, "application/json")
Catch ex As Exception
response = Me.Request.CreateResponse(HttpStatusCode.InternalServerError)
End Try
Return response
End Function
You need to return the $http object to the controller if I understand your question, hard to tell without seeing the controller though.

how to get JSON array value from internet

I want to get value of an array from JSON code in internet. from this URL : http://olympics.clearlytech.com/api/v1/medals/
after that, I want to display that array of my script without rewrite that JSON code on this URL http://olympics.clearlytech.com/api/v1/medals/
so, what code (script) that I can use?
for example, I want to display value from this array
var JSONs = {
example:['one','two','three']
};
the code is
document.write(JSONs.example[0]);
but if I want get the array value from the internet, what code/script that I can use?
Using jQuery, here is an example. In the success event, turn the resulting json text into a json object. You could also set the content type as json so you wouldn't have to call the JSON.parse().
$.ajax({
url: "http://olympics.clearlytech.com/api/v1/medals/",
success: function(data) {
var json = JSON.parse(data);
}
});
This is another way of doing the same i hope you asked how to parse through each value just try this in jsfiddle
$(document).ready(function(){
alert("here");
$.getJSON("http://olympics.clearlytech.com/api/v1/medals/",function(data){
$.each(data,function(key,value){
alert(data[key].country_name);
alert(data[key].rank);
console.log(data[key].rank));
});
});
});
public void handleResponse(String response)
{
// display("Response:"+response);
if(!response.equalsIgnoreCase(""))
{
JSONObject jso;
try {
jso = new JSONObject(response);
String status = jso.getString("status");
int valid=jso.getInt("valid");
// display("Welcome : "+UName);
if(valid>0)
{
if( status.equalsIgnoreCase("") || status==null || status.equalsIgnoreCase("Failed"))
{
invalid.setText("Invalid password");
//reset();
pwd.setText("");
}
else
{
//display(status);
intObj=new Intent(MainActivity.this,Design_Activity.class);
intObj.putExtra("Username", mUname);
startActivity(intObj);
MainActivity.this.finish();
}
}
else
{
invalid.setText("Invalid userid");
uname.setText("");
}
}
catch (JSONException e1) {
// TODO Auto-generated catch block
Log.e(TAG, e1.getLocalizedMessage(), e1);
}
catch(Exception e)
{
Log.e(TAG, e.getLocalizedMessage(), e);
}
}
else
{
display("Could not able to reach Server!");
}
}
Althought you want us to do everything, thats why your question went negative. Anyhow this is how you can do it in plain ajax
function getData(){
// Initialize the Ajax request
var xhr=new XMLHttpRequest();
xhr.open('get', 'http://olympics.clearlytech.com/api/v1/medals/');
// Track the state changes of the request
xhr.onreadystatechange=function(){
// Ready state 4 means the request is done
if(xhr.readyState === 4){
// 200 is a successful return
if(xhr.status === 200){
alert(xhr.responseText); // 'This is the returned text.'
}else{
alert('Error: '+xhr.status); // An error occurred during the request
}
}
}
// Send the request to send-ajax-data.php
xhr.send(null);
}

Resources