Passing an Object from Angular Post to .Net ASMX - json

I have been trying to pass an object as a Post parameter to .NET asmx web service. I can pass primitive types such as int, string as parameters but I would like to pass the whole object because my class contains a lot of properties and it is very time consuming to pass each property individually.
My c# web service code is:
[WebMethod(EnableSession = true)]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public ContactBLL AddContact(ContactBLL Contact)
{
//add contact and return the contact object
}
I have added following statement at the top of the web service class:
[System.Web.Script.Services.ScriptService]
I have a second function in the web service which I call when my page loads in order to get a json ContactBLL object.
[WebMethod(EnableSession = true)]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public ContactBLL GetContact(int ContactID)
{
//return contact
}
I use following functions in my factory to call asmx web methods:
factory.GetContactInfo = function (ContactID) {
return $http.post(serviceBase + 'GetContact', { ContactID: ContactID }).then(function (results) {
return results.data;
});
};
factory.InsertContact = function (Contact) {
return $http.post(serviceBase + 'AddContact', { ContactBLL: Contact }).then(function (results) {
return results.data;
});
};
In my controller, the GetContact function is called when the page loads and it returns the correct data to initialise the Contact object. I then call AddContact function and pass the object to factory function. The control doesn't get to the web service and I see the 500 message in chrome with the following message:
Message: "Invalid web service call, missing value for parameter: 'Contact'."
Here is the code for the controller:
var ContactController = function ($scope, $location, $http, $window, ContactService) {
var Contact;
Initialise();
function Initialise() {
Contact = {};
GetContact(-1);
}
function GetContact(ContactID) {
ContactService.GetContactInfo(ContactID)
.then(function (data) {
//do something
}, function (error) {
$window.alert('Sorry, an error occurred: ' + error.data.message);
});
}
$scope.AddContactRecord = function () {
ContactService.InsertContact(Contact)
.then(function (data) {
//do something
}, function (error) {
$window.alert('Sorry, an error occurred: ' + error.data.message);
});
}
}
Please let me know if I am doing anything wrong or an easy way for passing tens of properties via Post call. The GetContact call works fine, however, I get error on InsertContact call.

I have found the reason for the error. I was passing the datatype (ContactBLL) instead of the name (Contact) of the paramter in the AddContact function of my factory. The correct code is below:
factory.InsertContact = function (Contact) {
return $http.post(serviceBase + 'AddContact', { Contact: Contact }).then(function (results) {
return results.data;
});
};

Related

Login Service implementation in angularjs not working

This is my controller which is calling the login service
mod.controller("loginCtrl",function($scope,loginService,$http)
{
$scope.Userlogin = function()
{
var User = {
userid :$scope.uname,
pass:$scope.pass
};
var res = UserloginService(User);
console.log(res);
alert("login_succ");
}
});
And this is the login service code which takes the User variable and checks for username & password
mod.service("loginService",function($http,$q) {
UserloginService = function(User) {
var deffered = $q.defer();
$http({
method:'POST',
url:'http://localhost:8080/WebApplication4_1/login.htm',
data:User
}).then(function(data) {
deffered.resolve(data);
}).error(function(status) {
deffered.reject({
status:status
});
});
return deffered.promise;
// var response = $http({
//
// method:"post",
// url:"http://localhost:8080/WebApplication4_1/login.htm",
// data:JSON.stringify(User),
// dataType:"json"
// });
// return "Name";
}
});
I have created a rest api using springs which upon passing json return back the username and password in json like this
Console shows me this error for angular
You need to enable CORS for your application for guidance see this link
https://htet101.wordpress.com/2014/01/22/cors-with-angularjs-and-spring-rest/
I prefer to use Factory to do what you're trying to do, which would be something like this:
MyApp.factory('MyService', ["$http", function($http) {
var urlBase = "http://localhost:3000";
return {
getRecent: function(numberOfItems) {
return $http.get(urlBase+"/things/recent?limit="+numberOfItems);
},
getSomethingElse: function(url) {
return $http.get(urlBase+"/other/things")
},
search: function (searchTerms) {
return $http.get(urlBase+"/search?q="+searchTerms);
}
}
}]);
And then in your controller you can import MyService and then use it in this way:
MyService.getRecent(10).then(function(res) {
$scope.things = res.data;
});
This is a great way to handle it, because you're putting the .then in your controller and you are able to control the state of the UI during a loading state if you'd like, like this:
// initialize the loading var, set to false
$scope.loading = false;
// create a reuseable update function, and inside use a promise for the ajax call,
// which is running inside the `Factory`
$scope.updateList = function() {
$scope.loading = true;
MyService.getRecent(10).then(function(res) {
$scope.loading = false;
$scope.things = res.data;
});
};
$scope.updateList();
The error in the console shows two issues with your code:
CORS is not enabled in your api. To fix this you need to enable CORS using Access-Control-Allow-Origin header to your rest api.
Unhandled rejection error, as the way you are handling errors with '.error()' method is deprecated.
'Promise.error()' method is deprecated according to this and this commit in Angular js github repo.
Hence you need to change the way you are handling errors as shown below :
$http().then(successCallback, errorCallback);
function successCallback (res) {
return res;
}
function errorCallback (err) {
return err;
}
One more thing in your code which can be avoided is you have defined a new promise and resolving it using $q methods, which is not required. $http itself returns a promise by default, which you need not define again inside it to use it as a Promise. You can directly use $http.then().

MVC5 Retrieve data with ajax, return json object instead of view

I have a simple function that searches for item I want in my database and retrieves it in my controller.
[HttpPost]
public ActionResult Index(string searchString)
{
var user = from m in db.Users select m;
if (!String.IsNullOrEmpty(searchString))
{
user = user.Where(s => s.UserName.Contains(searchString));
}
return View(user);
}
And then in my Javascript I send a value to search:
$('#test').click(function(e) {
e.preventDefault();
var user = "John";
$.ajax({
url: "#Url.Action("Index", "Users")",
data { "searchString": user },
type: "post",
success: function (saveResult) {
console.log(saveResult);
},
error: function(xhr, ajaxOptions, thrownError) {
console.log(xhr, ajaxOptions, thrownError);
}
})
})
However of course all this does it return my view inside the console window which is something like:
But I would like to return a json object I can use.
just use the Json Action method.
return Json(user);
Edit:
As a side note, I would also set my return Type to be JsonResult for clarity
You just return as JsonResult such as below:
public ActionResult SomeActionMethod() {
return Json(new {foo="bar", baz="Blech"});
}

Backbone.js Service Call Event Binding

I'm new to Backbone, and I am trying to do a get request (getDivisions) and store the response JSON into 'divisions', defined in my defaults. I logged 'divisions' inside the service call, and outside the service call, as seen below.
define(['underscore', 'backbone', 'service-manager', 'backbone-nested'],
function(_, Backbone, svgmgr) {
return Backbone.NestedModel.extend({
defaults: {
message: "",
divisions: []
},
initialize: function () {
this.getDivisions();
},
getDivisions: function() {
var that = this;
svgmgr.Interface.call('getDivisions').done(function(data) {
that.set('divisions', data);
console.log("Inside the service call: " + that.get('divisions'));
});
console.log("Outside service call" + this.get('divisions'));
}
});
});,
In Dev Tools, the 'Outside the service call' log was called first, returning a blank array (it's default), while the 'Inside the service call' log was called after that, returning the correct response data. This is obviously not what I want.
How do I get this model to run this service call on initialize, so that when I reference 'divisions' I get back the response data?
First you don't need a Model but a Collection, and second Backbone can handle the ajax call for you.
So you have to do like this :
var Division = Backbone.Model.extend({
urlRoot: /* url to get a single division */,
defaults: {...}
});
var Divisions = Backbone.Collection.extend({
url: /* url to get all your divisions */,
model: Division,
initialize: function () {
this.fetch({
success: function(response) {
// you get the result here
}
});
}
});

to pass parameter to web api through ajax call

I have below ajax query which returns me json from controller
$(document).ready(function () {
$.getJSON(
"api/OutletPOC/GetHomeTab?bizId=1",
function (data) {
$("#homeTabDesc").append(data.HomeDesc);
$(".test").hide();
$("#hometabcontent").show();
});
});
the controller action is as below
[System.Web.Http.ActionName("GetHomeTab")]
public HomeTabModel GetHomeTab(int bizId)
{
var outlet = db.Info.Where(t => t.BizId == bizId).SingleOrDefault();
return new HomeTabModel
{
HomeDesc = outlet.BizHomeDesc,
HomeTabText = outlet.BizHomeTabText
};
}
Now my question is: curently i am sending hard coded value of bizId to web api. I want to send this value dynamically. How can i achieve this? I have that value in my route config file. The code is as below-
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{bizId}",
defaults: new { controller = "Home", action = "Index", bizId = 1 }
);
}
I am new to this. Please help! Thanks in advance!
no, actually after much research, i came up with this solution and this works fine for me....
In controller,
public ActionResult Index(int bizId)
{
ViewBag.BizId = bizId;
return View();
}
and in View,
$(document).ready(function () {
$.getJSON(
"api/OutletPOC/GetHomeTab?bizId=#ViewBag.BizId",
function (data) {
$("#homeTabDesc").append(data.HomeDesc);
$(".test").hide();
$("#hometabcontent").show();
});
});
You can pass a data object as part of the GetJson call.
$(document).ready(function () {
$.getJSON(
"api/OutletPOC/GetHomeTab",{bizId : 1},
function (data) {
$("#homeTabDesc").append(data.HomeDesc);
$(".test").hide();
$("#hometabcontent").show();
});
});
Taking this one step further you could wrap this in a function.
function makeCall(id)
{
$.getJSON("api/OutletPOC/GetHomeTab",{bizId : id},
function (data) {
$("#homeTabDesc").append(data.HomeDesc);
$(".test").hide();
$("#hometabcontent").show();
});
}
Also look into using promises.
$.getJSON().then().done();

zend_rest + mysql + backbone

I implemented a RESTful application with Zend_Rest that saves info in a mysql db.
I'm going to handle the view with Backbone.js.
I'm looking for just a simple CRUD example. How to do that?
I didn't found any examples with Zend_Rest+Backbone, and the idea is to create it here, together.
UPDATE 0.1
How can I send (from backbone) and read (in the get/put/delete controller) the parameters?
CONTROLLER (modules>api>controllers>BackboneController.php)
class Api_BackboneController extends Zend_Rest_Controller
{
public function init(){
$this->_helper->layout->disableLayout();
$this->_helper->viewRenderer->setNoRender(true);
}
public function headAction(){
$this->getResponse()->setBody(null);
}
public function optionsAction(){
$this->getResponse()->setBody(null);
$this->getResponse()->setHeader('Allow', 'OPTIONS, HEAD, INDEX, GET, POST, PUT, DELETE');
}
// called from backbone with "read"
public function indexAction(){
// get the params
$resp = json_decode(file_get_contents('php://input'));
// send the same response
$this->getResponse()->appendBody(json_encode($resp));
}
// I can't reach this one from backbone, WHY?
public function getAction(){}
// called from backbone with "update"
public function putAction(){}
// called from backbone with "delete"
public function deleteAction(){}
}
VIEW (modules>default>views>scripts>index.phtml)
var MyModel = Backbone.Model.extend({
defaults: {
text: "default text"
},
url: "/base/api/backbone",
options: {
success: function(data){
console.log(data);
},
error: function(x, t, e){
console.log("error: " + t + ", " + e);
}
}
});
var myModel = new MyModel();
Backbone.sync("read", myModel, myModel.options);
})(jQuery);