0

I have a problem with a form in my Web API. The form is very simple. The user enters a string, the controller receives the string and inserts it into a database with an id. The connection with the database works and I can read from it safely.

EDIT This is the code in the controller. EDIT 2 This is the correct and working controler

public ActionResult PostMyData(string json) 
{
        try
        {
            var newEntry = new Questions() { Id = json.Id, Question= json.Question};
            context.Questions.Add(newEntry);
            context.SaveChanges();
            return Ok();
        } 
        catch (Exception e)
        {
            return BadRequest();
        }
}

This is a part of the HTML page. EDIT This is the updated script that does not return errors. EDIT 2 This is the correct and working script

<script language="Javascript">
    $(document).on('click', '#submitButt', function () {
        var myquestion = $('#question').val();
        var json = {
            Id : 1,
            Question: myquestion
        }
        $.ajax({
            type: "POST",
            url: "api/Simple",
            data: JSON.stringify(json),
            dataType: "json",
            contentType:"application/json",
            success: function (data) {
                alert(data);
            },
            error: function (data) {
                alert("An Issue has occured");
            }
        });
    })
</script>
3
  • 1
    is there a question in here somewhere? Commented Feb 20, 2020 at 13:42
  • That isn't a question or a useful description of the issue. Please read What do you mean "it doesn't work"? Commented Feb 20, 2020 at 15:20
  • can you provide us the error ? and put your question in the post not in the coment , to be more helpful Commented Feb 20, 2020 at 15:23

1 Answer 1

1

Regarding your scenario, you can do something like this:

<input type="text" id="question" name="question" />
<input type="button" id="submitBtn" name="submitBtn" value="Send"/>

<script>
$(document).on('click', '#submitBtn', function () {
    var myquestion=$('#question').val();
    var json = {
      myquestion: myquestion
     };

     $.ajax({
       type: 'POST',
       url: "api/Simple/PostMyData",
       dataType: "json",
       data: JSON.stringify(json),
       contentType: "application/json",
       success: function (data) {
        alert(data);
       },
       error: function (data) {
        alert("An Issue has occured");
       }
    });
}) 
</script>

And your Controller will look like:

    using System.Web.Script.Serialization;

    [HttpPost]
    public ActionResult Post([FromBody] string json) 
    {
        var serializer = new JavaScriptSerializer();
        dynamic jsondata = serializer.Deserialize(json, typeof(object));

        //Get your variables here from AJAX call
        var myquestion= jsondata["myquestion"];
        try
        {
            var newEntry = new Question() { Id = 1, Question= myquestion};
            context.Question.Add(newEntry);
            context.SaveChanges();
            return Ok();
        } catch (Exception e)
        {
            return BadRequest();
        }
    }
Sign up to request clarification or add additional context in comments.

18 Comments

Thanks for the reply. However, the controller does not seem to be receiving the request. I believe the problem is in URL.
@Luiss.PEP Maybe there might be some error on the JS side. Also could you change the action method name to something more meaningful here like public ActionResult PostMyData(string json) . Also see my edit to the buttons that you have defined. I have added an id field
Are you able to hit the Controller method while debugging ? It might have to do with your db context.
Check you console on your browser. It will show if there are any errors in your script. Also you have not set id for your name input. Check updated answer.
In the end, thanks to you, I solved the problem. You can see the final solution in my question.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.