gtu
gtu

Reputation: 966

Sending simple type from HTML form to ASP API

I am having troubles with sending a simple double number from form to ASP API.

When I submit the form, I firstly need to remove Submit button to avoid sending a redundant 'submit=Submit' value to API controller.

As I have read in this article, I set the name of my input field to be empty. So if I check the http request in Developer mode, the body of sent data looks like so '=value'. My method parameter is decorated with [FromBody] attribute.

Even with all this, the controller method does not get the value. It is allways zero.

What to do?

My form looks like so:

 <form action="@Url.Action("Temperature","Api")" method="post" >
       <input type="number" name=" " step="0.25"/>
       <input type="submit" name="submit" />
   </form>
</div>

<script>
    $("form").submit(function () {
        $(this).children('[name="submit"]').remove();
    });
</script>

The controller:

    // POST: api/Temperature
    public void Post([FromBody]double value) //FormDataCollection data
    {            
        Temperature newEntry = new Temperature() { Timestamp = DateTime.Now, Value = value};
        try
        {
            db.Temperatures.Add(newEntry);
            db.SaveChanges();
        }
        catch(Exception e)
        {
            Debug.WriteLine(e.Message);
        }

    }

Upvotes: 0

Views: 974

Answers (1)

Masoud Andalibi
Masoud Andalibi

Reputation: 3228

Try Ajax...

Change your Html little bit like this:

 <div>
       <input type="number" id="number" name=" " step="0.25"/>
       <input type="button" id="submit" name="submit" />
</div>

Then:

$(document).on('click', '#submit', function () {
    $.ajax({
        type: 'POST',
        url: '/ControllerName/Post',
        data: {
            value: JSON.stringify($('#number').val())
        },
        success: function (data) {
            alert(data);
        },
        error: function (data) {
            alert("An Issue has occured");
        }
    });
})

Also your controller input parameters would be like:

public void Post([FromBody]string value) //convert string to double later within method 

Upvotes: 1

Related Questions