0

My goal is:

I am trying to send values into a method of my controller to update the database (which is connected remotely via API).

I have checked several tutorials (How to pass parameters in $ajax POST? for example) but I can not send the data in my controller I have a 500 error that is due to my ajax call.

Could you tell me what to do?

View

    $(document).ready(function () {
        $.ajax({
            url: "http://localhost:44338/Registration/ShowRegistration",
            type: 'POST',
            data: JSON.stringify({ "id": 1 }),
            contentType: 'application/JSON',
            success: function (data) { },
            error: function () { }
        })


    });

Controller

    [Authorize]
    [HttpPost]
    public async Task<ActionResult> ShowRegistration(Models.RegisterForm rF)
    {
        try
        {
            var test = rF.id;

            Ok("success");
        }
        catch (Exception e)
        {
            Console.Write(e.Message);
            return BadRequest();
        }
        return View();
    }

Model

public class RegisterForm
{
    public string id { get; set; }

}
Korpin
  • 323
  • 6
  • 24
  • 1
    A 500 is called "Internal Server Error" meaning that your server is throwing an exception. This could be because of invalid arguments sent to the api (have you debugged what the data is that you send?) or because some other problem in your server side code. Have you placed a breakpoint in your controller action in order to check what is going on? – Glubus Dec 06 '18 at 11:14
  • Yep but actually it doesnt enter in my controller, thats why i think the problem is directly related to my ajax declaration? – Korpin Dec 06 '18 at 11:30
  • i guess change contentType: 'application/json; charset=utf-8', and can you check datetime format – Hitesh Anshani Dec 06 '18 at 11:40
  • I've changed the contentType and now it enter in my Method Controller! But all the values are null... – Korpin Dec 06 '18 at 11:58
  • I think there is no need to use jquery.param for your data. – AlbertVanHalen Dec 06 '18 at 12:01
  • The data attribue is containing the values i need so maybe the problem is with the signature of my method controller? Like i cant pass all the attributes like i do? – Korpin Dec 06 '18 at 12:02
  • 1
    It should. I think the problem is that the date arguments (checkin, checkout) are not of type date but string. Parse these strings first to a date object and use toISOString method in your data object. – AlbertVanHalen Dec 06 '18 at 12:21
  • I just tried without the dates and my other values are still empty :/ But you were right for the dates, i need to add .toISOString() to send it as JSON – Korpin Dec 06 '18 at 12:24
  • can you now post your updated ajax call?? – Hitesh Anshani Dec 06 '18 at 12:33
  • Yep i edit it right now (i've put the whole view, maybe it will help)! I also create a specificmodel to receive the values of the ajax call, but it seems not to work.. – Korpin Dec 06 '18 at 12:40
  • check my answer @Korpin – Hitesh Anshani Dec 06 '18 at 12:51
  • 1
    Is the the whole app running on `https://localhost:44338/` Perhaps use a relative path to post to and if you have jQuery retrieving the value of a checkbox, it returns `on` and no `true` or `false`. You could use `.is(':checked')` – JP Hellemons Dec 06 '18 at 13:14
  • @Jp Hellemons Thanks, that was another problem i had :p – Korpin Dec 06 '18 at 13:23
  • What the path? Or posting the booleans? Because that can cause the object mapping (modelbinding) to fail. – JP Hellemons Dec 06 '18 at 13:27
  • To get the value of boleans instead of "on". But i have to say that i dont understand why is my model has only null values (or genereric like 0, false). Maybe i have to add JSON.stringify? – Korpin Dec 06 '18 at 13:30
  • Are you sure that `HttpContext.Session` is not null? And please, no empty `catch` statements. Please catch an Exception and return it or log it. – JP Hellemons Dec 06 '18 at 14:24
  • Yep, HttpContext.Session has a value of '571', the problem is my model who's coming empty (Models.InfoModel im), i dont get why its not populated with the ajax call values... – Korpin Dec 06 '18 at 14:38

1 Answers1

0

Create Model first now(Standard Way)

Try this and let me know.

public class InfoModel
{
    public string id { get; set; }
    //Add your model fields here
}

Your Api

        [HttpPost]
        public async Task<ActionResult> ShowRegistration(InfoModel im)
        {
          //code
        }

Your ajax call test this and then send more data:

$.ajax({
    url: "url",
    type: 'POST',
    data: JSON.stringify({"id": id}),
    contentType: 'application/JSON',
    success: function (data) {  },
    error: function () {};
}) 

Tested Example:-

   <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script>
        $(document).ready(function () {
            $.ajax({
                url: "http://localhost:62211/Home/ShowRegistration",
                type: 'POST',
                data: JSON.stringify({ "id": 1 }),
                contentType: 'application/JSON',
                success: function (data) { },
                error: function () { }
            })


        });
    </script>

</head>
<body>

</body>
</html>

Api

  using System.Threading.Tasks;
  using System.Web.Mvc;

namespace WebApplication5.Controllers
{
    public class HomeController : Controller
    {
        [HttpPost]
        public async Task<ActionResult> ShowRegistration(Models.info inf)
        {
            // Access inf.id 
            return null;
        }
    }
}
Hitesh Anshani
  • 1,499
  • 9
  • 19
  • Still null values (or 0 for int).. i edit my post to let you see my code. The strange thing is if i pass the id in the url it works.. like /id but the body does not work >.> – Korpin Dec 06 '18 at 13:00
  • Maybe i should add JSON.stringify? – Korpin Dec 06 '18 at 13:49
  • 1
    you should use JSON.parse – Hitesh Anshani Dec 06 '18 at 15:24
  • I've tried this: data: JSON.parse('{ "Status": status, "Cost": cost, "Terms": check1, "Info": check2 }'), but i've an error 'unexpected JSON parse token' – Korpin Dec 06 '18 at 15:39
  • Sorry my bad use json stringify https://www.w3schools.com/js/js_json_stringify.asp – Hitesh Anshani Dec 06 '18 at 16:18
  • Yup i tried with stringify but still the same.. >.> even when i only pass the id as you did in your example.. must be something else.. is it possible that the error occurs because of the model of my view which is not the same than the data model? – Korpin Dec 06 '18 at 16:21
  • Still the same with your code =/ (i had to modify stringify {} by () and inside of () i had to put only 'id' or it wasnt working at all. For the rest my value is still null – Korpin Dec 06 '18 at 16:29
  • now i have tested its working fine,is there anyway to check your code live?? – Hitesh Anshani Dec 06 '18 at 16:37
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/184828/discussion-between-korpin-and-d-john-anshani). – Korpin Dec 06 '18 at 16:38