here is JS code:
$.ajax({
url: 'http://localhost:8080/api/test/login',
type: 'POST',
data: {'loginEmail': loginEmail, 'loginPass': loginPass},
success: function (data) {
//do something
},
error: function(err) {
alert('Error ', err);
}
});
This is my controller:
#RestController
#RequestMapping("api/test")
public class TestController {
#PostMapping("/login")
public HttpStatus login(#RequestParam String loginEmail, #RequestParam String loginPass){
System.out.println(loginEmail);
System.out.println(loginPass);
return HttpStatus.OK;
}
}
I get this result:
image
image2
and I go to the error block...
What should my controller look like so that I get into the success block?
P.S I do not use Spring Security
Related
I'm new to programming and I want to pass a table input value to the controller. I tried this:
$("#btnsend").click(function () {
$.ajax({
type: "POST",
contentType: "application/json ; charset=utf-8",
data: {
buyerID: $('.BuyerID').val(),
},
url: "/SaveReservation",
success: function (data) {
alert('buyerID : ' + data);
},
error: function (result) {
alert('something went wrong');
}
})
});
The controller is like this :
[HttpPost]
[ValidateAntiForgeryToken]
public JsonResult SaveReservation(BuyerModel buyer)
{
return Json(buyer.DistibutorID);
}
When I click the button I get a success state but in the alert I get all the source code of the project after the word buyerID.
You may want to try this:
return Json(new { success = true, message = buyer.DistibutorID },
JsonRequestBehavior.AllowGet);
And:
alert('buyerID : ' + data.message );
Notice that this here in your script
data: {
buyerID: $('.BuyerID').val(),
},
Either must have the same structure as your BuyerModel Here
public JsonResult SaveReservation(BuyerModel buyer) <- BuyerModel that you are using
{
return Json(buyer.DistibutorID);
}
Or you can Just Change your Controller to accept only one argument Like this
public JsonResult SaveReservation(string buyerID) <- Follow the same Object structure you are passing in Ajax
{
return Json(buyer.DistibutorID);
}
My controller:
[HttpPost]
public IActionResult UserRoleChanged(string roleName,string userName)
{
var a = roleName;
var b = userName;
return RedirectToAction("UserManager");
}
Script in view:
if (window.confirm('Are you sure that you want to change role?')) {
jQuery.ajax({
type: "POST",
url: "#Url.Action("UserRoleChanged", "DashBoard")",
dataType: 'json',
data: { 'roleName': this.text, 'userName': 'SomeName'},
cache: false,
success: function (data){
window.location.href = data;
},
failure: function (data) {
}
})};
When I run script above UserRoleChanged action does not invoke. If I try to remove userName variable from data in ajax then UserRoleChanged action method invokes without any problem. How can i pass multiple data to my controller? What is wrong with my code?
Remove the dataType: 'json' from the ajax, and try again. As you are trying to get the values on server side as normal variable, so dataType: 'json' is not required here.
You can create a model with same properties and pass it as a parameter. Its a good practice.
Looks like this.
public class User
{
public string RoleName { get; set; }
public string UserName { get; set; }
}
And the json looks like this example
{
"RoleName" : "somename",
"UserName" : "somename"
}
i tried to call C# function through angular
i saw a template how to do it and i got this error.
o tried to look for a solution in google but it is kind pf general problem.
i am pretty sure that i did not adapt my code properly
this is the javascript code:
var app = angular.module("loginApp", []);
app.controller("loginC", ['$scope', '$http',function ($scope, $http) {
$scope.login = function () {
// $http.post('/login.aspx/Login', { userName: $scope.vm.username, password: $scope.vm.password });
var httpreq = {
method: 'POST',
url: 'login.aspx/Login',
data: { userName: $scope.vm.username, password: $scope.vm.password }
}
$http(httpreq).success(function (response) {
alert("Saved successfully.");
})
};
}]);
this is the C# function declaration(this function reside in login code behind file):
protected void Login(String userName,String password)
{
//some code
}
UPDATE
I changed the HTTP's configuration by adding "headers" to httpreq variable
var httpreq = {
method: 'POST',
url: '/login.aspx/Login',
headers: {'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'},
data: { username: $scope.vm.username, password: $scope.vm.password }
}
$http(httpreq).success(function () {
alert("Saved successfully.");
})
the error is gone and the alert is poped up , but i put BP at the beginning of the function in server side and i still cannot reach there,
i already tried to add [webmethod] and [HttpPost] decorate.
UPDATE2
when i changed the URL to
url: 'login.aspx'
(without the function name) and i set a BP at the PageLoad function ,i succeeded to reach the BP at the server side that mean the problem is with the path to the function.
what can i do?
Try this
var httpreq = {
method: 'POST',
url: '/login.aspx/Login',
headers: {'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'},
data: { userName: $scope.vm.username, password: $scope.vm.password }
}
$http(httpreq).success(function () {
alert("Saved successfully.");
})
[WebMethod]
[HttpPost]
protected static void Login(String userName,String password)
{
//some code
}
you are passing username in small whereas you used in webmethod in camelCase i.e userName. also use static webmethod.
I'm making a website with web API, I tried to send JSON to my controller but this is the error I keep getting.
Multiple actions were found that match the request:
Post on type AuctionWebsiteASP.Controllers.MovesController
readDatabase on type AuctionWebsiteASP.Controllers.MovesController
newItem on type AuctionWebsiteASP.Controllers.MovesController
First I tried searching for a fix but none of the fixes here helped.
My Controller
public class MovesController : ApiController
{
[AcceptVerbs("GET", "POST")]
public HttpResponseMessage Post([FromBody] Product product)
{
products.Add(product);
newItem();
return Request.CreateResponse(HttpStatusCode.OK, product);
}
}
My JS
$.ajax({
type: "POST",
dataType: "json",
url: "/api/moves/",
data: source,
success: function (data) {
$("#nStart").val(null);
$("#nImg").val(null);
$("#nMaker").val(null);
$("#nModel").val(null);
$("#nSerial").val(null);
$("#nCpu").val(null);
$("#nRam").val(null);
$("#nGpu").val(null);
$("#nStorage").val(null);
$("#nBattery").val(null);
$("#nDrivers").val(null);
$("#nAccessories").val(null);
$("#nNotes").val(null);
console.log("Data has been sent!");
},
error: function (error) {
jsonValue = jQuery.parseJSON(error.responseText);
alert("ERROR!");
}
});
Thanks in advance!
Your route is probably like this
routes.MapHttpRoute(
name: "API Default",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional });
But in order to have multiple actions with the same http method you need to provide webapi with more information via the route like so:
routes.MapHttpRoute(
name: "API Default",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional });
Try to use Route attribute to distinguish each action e.g
public class MovesController : ApiController
{
[Route("Product")]
public HttpResponseMessage Post([FromBody] Product product)
{
products.Add(product);
newItem();
return Request.CreateResponse(HttpStatusCode.OK, product);
}
}
$.ajax({
type: "POST",
dataType: "json",
url: "/api/moves/product",
data: source,
success: function (data) {
$("#nStart").val(null);
$("#nImg").val(null);
$("#nMaker").val(null);
$("#nModel").val(null);
$("#nSerial").val(null);
$("#nCpu").val(null);
$("#nRam").val(null);
$("#nGpu").val(null);
$("#nStorage").val(null);
$("#nBattery").val(null);
$("#nDrivers").val(null);
$("#nAccessories").val(null);
$("#nNotes").val(null);
console.log("Data has been sent!");
},
error: function (error) {
jsonValue = jQuery.parseJSON(error.responseText);
alert("ERROR!");
}
});
I have a Home controller whose view has a button.I want to call a controller named SearchSpace on button click.
View :
<script type="text/javascript">
var data = { "id": "1" }
function search() {
alert("hello" + JSON.stringify(data));
$.ajax({
url: '/SearchSpace/searchSpace',
type: 'POST',
dataType: "json",
contentType: 'application/json',
data: JSON.stringify(data),
success: function (returnPayload) {
console && console.log("request succeeded");
},
error: function (xhr, ajaxOptions, thrownError) {
console && console.log("request failed");
}
});
}
</script>
Controller
[HttpGet]
public ActionResult searchSpace()
{
return View();
}
[HttpPost]
public ActionResult searchSpace(SearchSpace search)
{
//code
return View();
}
Route Config
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
alert is calling but it is not moving to SearchSpace Controller..
Please help me.
try this
<button id="click">Click me
</button>
Problem is with data type that jQuery.ajax() is expect, since you assign dataType property with json. From jQuery API documentation:
dataType (default: Intelligent Guess (xml, json, script, or html))
Type: String
The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string). The available types (and the result passed as the first argument to your success callback) are:
..."json": Evaluates the response as JSON and returns a JavaScript object. The JSON data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown. As of jQuery 1.9, an empty response is also rejected; the server should return a response of null or {} instead. (See json.org for more information on proper JSON formatting.)
There are at least 2 ways to solve the problem:
First, Omit dataType property:
$.ajax({
url: '/SearchSpace/searchSpace',
type: 'POST',
contentType: 'application/json',
//dataType: "json", << delete this line or comment it
data: JSON.stringify(data),
success: function (data) {
console && console.log(data);
},
error: function (xhr, ajaxOptions, thrownError) {
console && console.log("request failed");
}
});
Second, return JSON type data from response:
[HttpPost]
public ActionResult searchSpace(int? id)
{
if (Request.IsAjaxRequest() && id != null)
{
return Json(new { data = "Requested data is: " + id.ToString() });
}
return View();
}