I am using angularjs and ionic.I post multiple data from angular js to Api Controller in asp.net mvc
I have below code in order to post multiple form data to controller in asp.net mvc from angularjs.
$http({
method: 'POST',
url: 'http://localhost:51425/api/values/Response',
params: { PropertyFirst: "1", PropertySecond: "2" },
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
}).success(function (data) {
alert("ok");
});
If i use below code this works
[HttpPost]
public object Response(string PropertyFirst , string PropertySecond)
{
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
return null;
}
However, if i use below code it is not working
PropertyClass
public string PropertyFirst{ get; set; }
public string PropertySecond{ get; set; }
Controller side
[HttpPost]
public object Response(PropertyClass propertyValues)
{
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
return null;
}
I get below error :
Failed to load resource: the server responded with a status of 500 (Internal Server Error)
Question:
How can i post PropertyFirst and PropertySecond to PropertyClass ?
Any help will be appreciated.
Thanks.
From the Angular $HTTP docs :
params – {Object.} – Map of strings or objects which will be serialized with the paramSerializer and appended as GET parameters.
I don't know much about asp MVC framework, but if you change the 'params' key to a 'data' key, your request will be correct.
Unfortunately I can't really help with the ASP controllers, as I am entirely unfamiliar with that language.
Related
i use .net and send js(ajax) two data to .net controller
in data test1 and test2 is json data.
.ajax({
type: 'POST',
url: "/test/test_Put/",
contentType: 'application/json; charset=utf-8',
data: {json_1:JSON.stringify(test1), json_2:JSON.stringify(test2)},
dataType:'JSON',
success:function(data){
},
error: function (data) {
}
});
.net controller
[HttpPost]
public JsonResult test_Put([FromBody]test1 tt1, [FromBody]test2 tt2){
}
but i saw error ㅜㅜ
how should i handle it in .net
You should only have 1 [FromBody] in your action.
https://learn.microsoft.com/en-us/aspnet/core/mvc/models/model-binding?view=aspnetcore-2.1
There can be at most one parameter per action decorated with
[FromBody]. The ASP.NET Core MVC run-time delegates the responsibility
of reading the request stream to the formatter. Once the request
stream is read for a parameter, it's generally not possible to read
the request stream again for binding other [FromBody] parameters.
Create a wrapper class for this instead.
public class TestRequest
{
public test1 json_1;
public test2 json_2;
}
[HttpPost]
public JsonResult test_Put([FromBody]TestRequest data){}
BTW, you should use camel case in your method and variable names.
I am learning Spring MVC and I have stuck at how to send a simple string value from client using AJAX and print it at JAVA server (controller). I have written below code for doing this. But when I click button to send string, error.... response is popped-up in my browser and the browser console displays POST http://localhost:8090/addUser 404 (). It has been a day since I am trying to solve this issue. Can someone please tell what can be the problem? Or please tell a working alternative solution for sending data from client using AJAX and printing/saving it on JAVA server (Spring-MVC).
UserController.java
#Controller
public class UserController {
#RequestMapping(value = "/addUser", method = RequestMethod.POST, consumes=MediaType.APPLICATION_JSON_VALUE, produces=MediaType.APPLICATION_JSON_VALUE)
public JSONArray addUser(#ModelAttribute("UserTest") JSONArray name) {
System.out.println(name.toString());
return name;
}
}
AJAX Request:
<script>
function addUser() {
var json = '{"uname":"John", "Age":42}';
obj = JSON.parse(json);
$.ajax({
url : "/addUser",
data : obj,
type : "POST",
async: false,
contentType: "application/json",
success : function(response) {
alert( response );
},
error : function() {
alert("error...."); //this is being popped-up in my browser
}
});
}
</script>
POST http://localhost:8090/addUser 404 ()
Your request is going to http://localhost:8090/addUser, which is not correct. Your request url should have your application and included.
http://localhost:8090/<app_name>/addUser
AFAIK, your request url should have application name included. Now, to achieve this, you are suppose to change your ajax url
url : "/<app_name>/addUser"
The URL for the ajax call is not correct. It should be like
Url:YourApplicationContextPath/ControllerName/addUser
I've looked at thousands of articles about my problem, but i didn't found a solution.
Here we go.
When I'm using ajax with url specified as the url of view when i want to use a script it doesn't work. I'm using POST type and receiving data in spring controller. When I change url to something else and do the same in requestmapping value, everything works fine. What possibly causing this problem ? AJAX:
$.ajax({
type : "POST",
url : "/login2",
data :
{x: x}
,
success : function() {
alert('fine');
},
error: function(xhr, status, error) {
alert(xhr.status+status+error);
}
});
SPRING:
#Controller
#RequestMapping
public class LoginController {
#RequestMapping(value = "/login",method = RequestMethod.GET)
public String login() {
return "login";
}
#RequestMapping(value = "/login2",method =RequestMethod.POST)
public #ResponseBody void login2(#RequestParam(value="x[]") String x[]){
System.out.println(x[1]);
}
}
Code above works fine but
When url is "/login" for whole class and methods are specified the same it doesn't work ..
Can You help me please ?
Your parameter for login2 is array of string. Whereas you are sending object from ajax.
try reading the values from Request body instead of request param.
login2(#RequestBody String x[])
Maybe problem is that this is my page declared as login apge in Spring Security ?
In an ASP.NET MVC project, I have a controller method that accepts POST requests, like so (with the "User" class for completeness):
[HttpPost]
public ActionResult TestMethod(User user)
{
return Content("It worked");
}
public class User
{
public string Name { get; set; }
public string Email { get; set; }
}
I call this method with jQuery Ajax:
$.ajax({
url: '/test/TestMethod/',
data: JSON.stringify({ user: { name: 'NewUserName', email: 'username#email.com' } }),
type: 'POST',
success: function (data) {
alert(data);
},
error: function (xhr) {
alert('error');
}
});
When I create a fresh ASP.NET MVC project, and include this code in a new Test controller, everything works fine. Viewed through Fiddler, a single POST request is made, and I get the controller method return value back.
However, when I run this code in the current MVC project that I'm developing, it doesn't work. From Fiddler I see that the ajax call first initiates a POST method, that gets a 301 http status error ("moved permanently"?). Immeditely afterwards a GET request is made, which generates a 404 not found error (which makes sense as there is no GET action method with this name available).
So I use the exact same code, in a fresh projects and in the existing project, but the code only works in the fresh project. So clearly there's something about my existing project that somehow prevents this from running properly (and causes the odd behaviour of generating both a POST and a GET request). But I have no idea what it could be, so any suggestions welcome...!
Update - routing information:
public static void RegisterRoutes(RouteCollection routes)
{
routes.AppendTrailingSlash = true;
routes.MapMvcAttributeRoutes();
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional });
}
Update 2:
Looks like this issue is caused by Content Security Policy settings that were switched on for this project.
You need to put the [FromBody] annotation before your method's argument.
[HttpPost]
public ActionResult TestMethod([FromBody]User user)
{
return Content("It worked");
}
ASP.net MVC framework will use the arguments you pass in the body to recognize the method.
I ran into this issue after I implemented Custom Errors, and My form was posting a File back to the server tthat was larger than the Max Allowed. This resulted in a 404.13 error... I guess that is the default error for "file too large"
When custom errors were turned on all I saw was the 404. It was driving me crazy that I was getting a 404 error when I knew that the request type was a post, and the url where it was posting was correct.
Hope this helps someone.
I have a very simple .NET Web API hosted in Azure, with two very simple methods:
[EnableCors(origins: "http://simpleapiearl.azurewebsites.net", headers: "*", methods: "*")]
public class EnvelopesController : ApiController {
// GET: api/Envelopes
public IEnumerable<string> Get() {
return new string[] { "value1", "value2" };
}
// POST: api/Envelopes
public string Post([FromBody]Envelope env) {
return "rval: " + env + " (and my addition to env)";
}
}
I have created a simple plunk to call these methods. In my AngularJS code, I'm making two very simple $http calls. The GET works fine. The POST, however, always returns a "400 (Bad Request)", followed shortly in my WebStorm console by "XMLHttpRequestion cannot load ... Invalid HTTP status code 400".
Any and all suggestions appreciated!
EDIT!!
Hello, and thanks for the very fast responses. I just realized I forgot to add some very relevant detail.
The parameter to my POST method is what I call an Envelope object, which contains two properties: listingId (int), and Description (string). When I add the urlencoded Content-Type header, and pass '{"listingId":1234, "Description":"some description"}' as my POST data, the env parameter in my POST method on the server is NULL (that is, it seems unable to parse the JSON I'm providing). Sorry this was omitted from original post.
I think this post would be helpful.
How do I POST urlencoded form data with $http in AngularJS?
By default, the $http service will transform the outgoing request by
serializing the data as JSON and then posting it with the content-
type, "application/json". When we want to post the value as a FORM
post, we need to change the serialization algorithm and post the data
with the content-type, "application/x-www-form-urlencoded".
This is the modified plnkr from yours. Your code is missing conversion of JSON to encoded url.
http://plnkr.co/edit/4aeEDz73qgHSfOv1sBgn?p=preview
$http({
method: 'POST',
url: 'http://simpleApiEarl.azurewebsites.net/api/envelopes',
data: env,
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
transformRequest: function(obj) {
var str = [];
for(var p in obj)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
return str.join("&");
}
}).
I found a blog post that corrected my issue:
http://victorblog.com/2012/12/20/make-angularjs-http-service-behave-like-jquery-ajax/
Thanks to everyone for helping me out!
With AngularJS you can do in an easier way.
You can inject $httpParamSerializer and then prepare your data through $httpParamSerializer(data).
So your call should look something like:
$http({
method: 'POST',
url: 'http://simpleApiEarl.azurewebsites.net/api/envelopes',
data: $httpParamSerializer(env),
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})