2

I am using asp.net 4.5 and latest MVC version. I need retrive deviceId and body from header when posting the form in the html page. At line public void Post([FromBody]string value) value it is always null.

Wha am I doing wrong here?

  namespace WebApi.Controllers
    {
        public class NotificationController : ApiController
        {
            // GET api/notification
            public IEnumerable<string> Get()
            {
                return new string[] { "value1", "value2" };
            }

            // GET api/notification/5
            public string Get(int id)
            {
                return "value";
            }

            // POST api/notification
            public void Post([FromBody]string value)
            {
// value it is always null
            }

            // PUT api/notification/5
            public void Put(int id, [FromBody]string value)
            {
            }

            // DELETE api/notification/5
            public void Delete(int id)
            {
            }
        }
    }


<form action="/api/notification" method="post">
    DeviceId: <input name="deviceId" value="gateeMachine">
    Body: <input name="body" value="Warning Out of Paper">
    <button>Tes send</button>
</form>
GibboK
  • 71,848
  • 143
  • 435
  • 658

2 Answers2

4

The model binder matches the parameters to the values from the name attributes in your form. I find it's less of a headache to create models though (the following is untested code):

public class Devices
{
     public string DeviceId { get; set; }
     public string Body { get; set; }
}

The Action:

public void Post(Devices device)
{

}

The form:

<form action="/api/notification" method="post">
    Device Id: <input name="DeviceId" value="gateeMachine">
    Body: <input name="Body" value="Warning Out of Paper">
    <button>Test send</button>
</form>

-- EDIT: It turns out that binding multiple form values isn't supported (see this answer), so the model is the way to go. You could serialize your form values into the querystring. You could also serialize the values into a single string (i.e. JSON or XML) and then deserialize server-side, but really, the model is the most straight forward path here.

Community
  • 1
  • 1
andes
  • 514
  • 3
  • 6
  • using first approach wihtout model i get Can't bind multiple parameters ('deviceId' and 'body') to the request's content... any idea? – GibboK Nov 27 '13 at 14:10
  • do you have an idea why ([FromBody]string deviceId, [FromBody]string body) does not work? – GibboK Nov 27 '13 at 14:16
0

well your post is accepting one parameter 'value' and you are trying to send it two parameters 'deviceId' and 'body'. Fixing that would be a good place to start.

Jonesopolis
  • 25,034
  • 12
  • 68
  • 112