Luiss.PEP
Luiss.PEP

Reputation: 27

Form in ASP.NET Web API

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>

Upvotes: 0

Views: 97

Answers (1)

Rahul Sharma
Rahul Sharma

Reputation: 8311

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();
        }
    }

Upvotes: 1

Related Questions