Pass data using http post in angularjs and Asp .Net Web Api - asp.net

I am trying to use post method of Web API from angularjs code but the data that I am sending from $http is not reaching to Web API method. The planDetailsVM parameter remains null. Below is my code-
Web API Controller code-
public class RateCalculationController : ApiController
{
[HttpPost]
public RateCalcOutParmDTO GetPlanRateCalculation(PlanDetailsVM planDetailsVM)
{
//planDetailsVM remains null
RateCalcOutParmDTO rateCalcOutParmDTO = new RateCalcOutParmDTO();
// Some operation here
return rateCalcOutParmDTO;
}
}
Here planDetailsVM remains null.
AngularJs Code-
$http({
url: key_Url_GetPlanRateCalculation,
method: 'Post',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
params: $scope.PlanDetails
}).then(function (result) {
//Some operation here
});
Route mapping code-
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
var appXmlType = config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(t => t.MediaType == "application/xml");
config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType);
}
I tried to follow one of the solution at this link AngularJs $http.post() does not send data but it's not working for me. What can I need to do so that planDetailsVM receives the posted data from AngularJS http post?
PlanDetails data-
$scope.PlanDetails = { QuoteName: null, BenefitAmountId: 0, BenefitAmountValue: null, DoD_Id: 0, DoD_Value: null, EPBD_Id: null, EPBD_Value: null, _DisplayMsg: null, _DisplayFlag: false };

I was able to solve this issue by just replacing key "params:" with "data:" in the https post request as suggested by Ben. Below is the angularJS code that did the work-
$http({
url: key_Url_GetPlanRateCalculation,
method: 'Post',
data: $scope.PlanDetails
}).then(function (result) {
//Some operation here
});

Related

Can't send data with $http.post in Ionic Framework

I'm trying make an application with Ionic framework which can take and send data to MS SQL server. For this I am using web api. I have no problem with taking data but something wrong with send new datas. Here is my ionic code :
angular.module('starter.controllers',[])
.controller('CheckListCtrl', function($scope, ChecklistService, $ionicPopup) {
function addCheck(){
ChecklistService.addCheck()
}
.factory('ChecklistService', ['$http', function ($scope, $http) {
var urlBase = 'http://localhost:56401/api';
var CityService = {};
CityService.addCheck = function(){
var url = urlBase + "/TBLCHECKLISTs"
var checkdata = {
AKTIF : true,
SIL : false,
KAYITTARIHI : Date.now(),
KULLANICIID : 3,
BASLIK : "Onur",
TAMAMLANDI : false,
TAMAMLANMATARIHI : null,
GUN : 1
}
var request = $http({
method: 'POST',
url: url,
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: checkdata
});
return request;
}
return CityService;
}]);
And here is my web api:
[HttpPost]
[ResponseType(typeof(TBLCHECKLIST))]
public IHttpActionResult PostTBLCHECKLIST(TBLCHECKLIST tBLCHECKLIST)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
tBLCHECKLIST.KAYITTARIHI = DateTime.Now;
db.TBLCHECKLISTs.Add(tBLCHECKLIST);
db.SaveChanges();
return CreatedAtRoute("DefaultApi", new { id = tBLCHECKLIST.TABLEID }, tBLCHECKLIST);
}
When i try to send i get this exception:
After, I realize that I take that exception because my checkdata is never come to web api. I don't know why.
These are not the datas I send:
I have tried different versions of post request but nothing. When I try to send data with PostMan, it works and I can insert data to my database. But why I can't do it with my application? Can anybody help me?
I think this should be the problem:
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
Try this:
return $http.post(url, checkdata);
And in your API:
[HttpPost]
[ResponseType(typeof(TBLCHECKLIST))]
public IHttpActionResult PostTBLCHECKLIST([FromBody]TBLCHECKLIST tBLCHECKLIST)
{
//code here
}
Also, make sure your checkdata properties match the ones in your TBLCHECKLIST c# type.

Response for preflight has invalid HTTP status code 500 says

I have a web api in asp.net 4.5. I have installed nuget package for cors
and made corresponding code changes
in WebApiConfig.cs:
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
config.EnableCors();
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
In the controller
[EnableCors(origins: "http://localhost:56241/api/loancopy/3219795539", headers: "*", methods: "*")]
[RoutePrefix("api/loancopy")]
public class MainController : ApiController
{
[HttpPost]
[Route("{loannumber}")]
public HttpResponseMessage PostLoanCopy([FromUri]string loanNumber, [FromBody] LoanDto LoanDto)
{
return new HttpResponseMessage();
}
}
This is my client side post request in angular2
export class HeroService {
private heroesUrl = 'http://localhost:56241/api/loancopy/3219795539';
private body = 'body'
constructor(private http: Http) { }
addHero(name: Loan): Observable<Loan> {
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
return this.http.post(this.heroesUrl, JSON.stringify(Loan), options)
.map(this.extractData)
.catch(this.handleError);
}
My client says Response for preflight has invalid HTTP status code 500
Looking at your code I presume you followed this documentation
I'm finding it strange that the URL your client calls is exactly the same as the url declared as acceptable origins:
Angular2:
private heroesUrl = 'http://localhost:56241/api/loancopy/3219795539';
WebApiConfig.cs
[EnableCors(origins: "http://localhost:56241/api/loancopy/3219795539", ...
The origins parameter is used to indicate from which hosts do you accept incomming requests, and the value you seem to be using is the exact same host as the .net application is running. Consider changing it to the host you are accessing your angular2aplication.
For example, if you are running it in localhost, on port 3000, the EnableCors declaration should be the following:
[EnableCors(origins: "http://localhost:3000", headers: "*", methods: "*")]
Also, as #Developer noted, the origin declaration should not contain the path, just the host.
So use something like origins: http://localhost:3000 instead of http://localhost:3000/path/to/angular/page

How to make an Ajax call to action method in different controller

I have following scenario.
Route Config:
routes.MapRoute(
name: "SellerRegistration",
url: "Registration/{action}/{id}",
defaults: new { controller = "SellerRegistration", action = "Seller", id = UrlParameter.Optional, area = "" },
namespaces: new[] { "MyCompany.Controllers" }
);
So when the url is www.example.com/Registration/Seller, the above route will match and displaying the view without any issues.
class SellerRegistration
{
public ActionResult Seller()
{
return View("Seller");
}
[AjaxOnly]
public bool ValidateUserEmail(string email)
{
return _userService.ValidateUserEmail(email);
}
}
Inside my view Seller.cshtml, I'm trying to make an ajax call to the method ValidateUserEmail().
I'm making ajax call as below:
$.ajax({
type: "POST",
url: rootUrl + "/SellerRegistration/ValidateUserEmail",
cache: false,
async: false,
data: { email: $("#Email").val() },
success: function (data) {
if (data === 'True') {
//redirect to login page
window.location.href = newUrl;
} else {
$("#otherDetails").show();
$("#emailValidation").hide();
$("#submitCompleteFormDiv").show();
}
},
error: function (data, jqXhr) {
console.log(jqXhr.status);
}
});
I have also tried generating url as below in the above ajax method.
url: '#Url.Action("SellerRegistration", "ValidateUserEmail")'
But I'm getting
401 - Unauthorised error.
I'm guessing that I'm not able to make ajax call because of the routing I configured. But, that routing is required to meet other scenarios in the application.
When ajax call is made, the url format is like www.example.com/Registration/Seller
So browser initiates an ajax call to the ValidateUserEmail method inside the controller SellerRegistration from www.example.com/Registration/Seller.
Because there is no real controller named Registration, when the ajax call is made to ValidateUserEmail() inside SellerRegistration controller, I'm getting 401 Unauthorized error.
Can someone please suggest if there is any technique or workaround to make it possible.
Thank you.

web api returned content missing when posting in angularjs

I am trying to post data and return some content posting to a .net web api using angularjs
here is my web api
[HttpPost]
public HttpResponseMessage Post()
{
return new HttpResponseMessage()
{
Content = new StringContent(
"<strong>test</strong>",
Encoding.UTF8,
"text/html"
)
};
}
and here is my post from my client
$http({
url: 'my happy url',
method: "POST",
data: objData,
headers: {
'Content-Type': 'text/html'
}
}).success(function (data, status, headers, config) {
console.log(headers());
}).error(function (data, status, headers, config) {
console.log("error");
});
my problem is I do not get any data returned. I am sure I am missing something simple. Thanks for your help.
in the above code the data parameter is empty and I would expect to find the string "test" in the data parameter.
Instead of HttpResponseMessage, can you try to use IHttpActionResult? Sample code as below.
public IHttpActionResult PostSample()
{
return Content(HttpStatusCode.OK, "Test String");
}

In asp.net mvc 4.0 Multiple save methods not working in api controller

I am working with asp.net MVC 4.0,In my API Controller I am having two save methods which are called through AJAX calls.The issue is both of them are not working simultaneously i.e the method doesn't get called.
If i comment one the other works fine
Sample Code of APIController:
[HttpPost]
public IEnumerable<Model1> Save1 (Model1 model1)
{
//code
}
[HttpPost]
public IEnumerable<Model2> Save2(Model2 model2)
{
}
Code of json :
$.ajax
({
url: "/api/Myapi/Save1",
type: 'POST',
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(model1),
success: function (data) {
alert("success");
return true;
}
});
similar code for Save2 Method
Please suggest.
If you want to violate the standard RESTful routing convention and use custom names for your actions you will have to define a custom route in your WebApiConfig containing the {action} part in it:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
The RESTful routing convention dictates that you should have a single action per HTTP verb and per resource (i.e API controller).

Resources