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!");
}
});
Related
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
I am passing values to the action method using the ajax call. My action method name is TagTargets and this method has three parameters. I am also giving the exact path also but getting the error The resource cannot be found.
//Ajax Call to get targets Data
function TargetsData() {
var realTags = $('#Raw_Tag_List').val();
var calculatedTags = $('#Calculated_Tag_List').val();
var manulTags = $('#Manual_Tag_List').val();
$.ajax({
url: 'TagTargets',
type: 'Post',
contentType: 'application/json',
dataType: 'json',
data: { 'RealTags': realTags, 'CalculatedTags': calculatedTags, 'ManulTags':manulTags},
success: function (data) {
if (data.success) {
alert('Ok')
}
else {
alert('Not ok');
}
}
});
debugger;
}
//Action Method
[HttpPost]
public JsonResult TagTargets(List<string> RealTags, List<string> CalculatedTags, List<string> ManulTags)
{
return Json(true);
}
change your url to a valid url.
url: "#Url.Action("TagTargets","ControllerName");",
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);
}
I´ve got a problem with my current mvc project.
I´m using an ajax call to send new comments to the server but the method does not even get called.
My js code:
$("#answer_button").click(function () {
showLoadingTab();
var actionUrl = '#Url.Action("AnswerThread", "Threads")';
var threadId = $("#threadId").val();
var msg = $("#answer_msg").val();
alert(actionUrl);
alert(msg);
alert(threadId);
$.ajax({
url: actionUrl,
type: "POST",
data: "Message=" + msg + "&threadId=" + threadId,
success: function (msg) {
hideLoadingTab();
location.reload();
},
error: function () {
alert("Ein Fehler ist aufgetreten.");
hideLoadingTab();
}
});
});
as you see I´ve alerted the url, msg and threadId and they are all correct. url: "/Threads/AnswerThread", msg: "test", threadId: 1.
I´ve already tried to put a breakpoint inside the AnswerThread method but it does not get called. The "AnswerThread" method is inside the "ThreadsController" and looks like this:
[HttpPost]
public ActionResult AnswerThread(string Message, int threadId)
{
var userId = User.Identity.GetUserId();
using (var db = new UnitOfWork(new BlogContext()))
{
db.Posts.Add(new Post()
{
Message = Message,
PublishTime = DateTime.Now,
ThreadId = threadId,
UserId = userId
});
db.Complete();
}
return PartialView("/Views/Partial/Clear.cshtml");
}
That´s exactly the same way I did it in the backend controllers but there it just works fine.
I hope somebody can help me..
UPDATE:
Made some changes just to try if any other way works.
Change1 js:
var data = {
threadId: threadId,
Message: msg
};
$.ajax({
url: actionUrl,
type: "POST",
content: "application/json; charset=utf-8",
dataType: "json",
data: data,
success: function (msg) {
if (msg.success == true) {
hideLoadingTab();
location.reload();
}
else
{
alert("Ein Fehler ist aufgetreten: " + msg.error);
}
},
error: function () {
alert("Ein Fehler ist aufgetreten.");
hideLoadingTab();
}
});
Change 2 c#:
[HttpPost]
public JsonResult AnswerThread([System.Web.Http.FromBody]PostDataModel data)
{
var userId = User.Identity.GetUserId();
string error = "";
bool success = false;
try
{
using (var db = new UnitOfWork(new BlogContext()))
{
db.Posts.Add(new Post()
{
Message = data.Message,
PublishTime = DateTime.Now,
ThreadId = data.threadId,
UserId = userId
});
success = true;
db.Complete();
}
}
catch(Exception ex)
{
error = ex.Message;
}
return Json(String.Format("'Success':'{0}', 'Error':'{1}'", success, error));
I tried this now with and without the "[FromBody]" statement.
Oh yes and I´ve added the DataModel like this:
public class PostDataModel
{
public int threadId { get; set; }
public string Message { get; set; }
}
and I also tried to manually configure the pointed route.
routes.MapRoute(
name: "AnswerThread",
url: "threads/answer",
defaults: new { controller = "Threads", action = "AnswerThread" }
);
The "actionUrl" variable in js get´s changed to /threads/answer but I´m always getting 500 Internal Server Error. When I put a breakpoint inside the method it does not stop at any point of the ajax call.
In the Chrome Dev Tools at the "Network" tab it says to me that there is a parameter called "id" which is null which causes to this 500 internal server error. I tried to find out more information about this but the error does not tell me where this parameter is located.
I´ve got no parameter called "id" inside this method or the data model so where does this come from?
Solution:
My Routes mapping was bad. I first mapped the route /threads/{id} and THEN did /threads/answer so when the /threads/answer got called it thought "answer" is an id so it tried to enter the "Index" method. So for my particular problem (and maybe for some other guys having the same issue) the solution was just to put the mapping of the /threads/answer route in front of the /threads/{id} route and it worked.
Please check your parameter types, in controller threadId is int type and from ajax call you are passing string type.
In Js
$("#answer_button").click(function () {
showLoadingTab();
var actionUrl = '#Url.Action("AnswerThread", "Home")';
var threadId = parseInt($("#threadId").val());
var msg = "Answer message";
alert(threadId);
$.ajax({
url: actionUrl,
type: "POST",
data: { Message: msg, threadId: threadId },
success: function (msg) {
hideLoadingTab();
location.reload();
},
error: function () {
alert("Ein Fehler ist aufgetreten.");
hideLoadingTab();
}
});
});
In Controller
[HttpPost]
public ActionResult AnswerThread(string Message, int threadId)
{
return Json("Data");
}
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"
}