[c#] Simple post to Web Api

I'm trying to get a post request to work with the web api. Following is my api controller.

public class WebsController : ApiController
{
    [HttpPost]
    public void PostOne(string id)
    {
    }

    [HttpPost]
    public void PostTwo(Temp id)
    {
    }
}

I have altered the webapi route to take the action into account. the Temp model look something like this.

public class Temp
{
    public string Id { get; set; }
}

my view look something like this

@using (Ajax.BeginForm(new AjaxOptions
{
    Url = "/api/webs/postone",
    HttpMethod = "post"
}))
{
    <input name="id" id="id" value="2" />
    <input type="submit" value="submit" />
}

the above code does not work at all with the postone unless I put the [FromBody] attribute in front of the parameter like this.

[HttpPost]
public void PostOne([FromBody]string id)
{
}

then it hits the action, but the id is still null. It doesn't get populated with the value in the textbox.

But, if I change the Url of the Ajax.BeginForm to posttwo which take the model Temp, it works nicely and the Id field gets the proper value in the textbox.

can anyone please explain me the reason for this to happen and how I can post a simple value to a web api action? I mean, why can it bind a complex type but not a simple type.

This question is related to c# asp.net-mvc-4 asp.net-web-api http-post

The answer is


It's been quite sometime since I asked this question. Now I understand it more clearly, I'm going to put a more complete answer to help others.

In Web API, it's very simple to remember how parameter binding is happening.

  • if you POST simple types, Web API tries to bind it from the URL
  • if you POST complex type, Web API tries to bind it from the body of the request (this uses a media-type formatter).

  • If you want to bind a complex type from the URL, you'll use [FromUri] in your action parameter. The limitation of this is down to how long your data going to be and if it exceeds the url character limit.

    public IHttpActionResult Put([FromUri] ViewModel data) { ... }

  • If you want to bind a simple type from the request body, you'll use [FromBody] in your action parameter.

    public IHttpActionResult Put([FromBody] string name) { ... }

as a side note, say you are making a PUT request (just a string) to update something. If you decide not to append it to the URL and pass as a complex type with just one property in the model, then the data parameter in jQuery ajax will look something like below. The object you pass to data parameter has only one property with empty property name.

var myName = 'ABC';
$.ajax({url:.., data: {'': myName}});

and your web api action will look something like below.

public IHttpActionResult Put([FromBody] string name){ ... }

This asp.net page explains it all. http://www.asp.net/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api


Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to asp.net-mvc-4

Better solution without exluding fields from Binding How to remove error about glyphicons-halflings-regular.woff2 not found When should I use Async Controllers in ASP.NET MVC? How to call controller from the button click in asp.net MVC 4 How to get DropDownList SelectedValue in Controller in MVC Return HTML from ASP.NET Web API There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key country Return JsonResult from web api without its properties how to set radio button checked in edit mode in MVC razor view How to call MVC Action using Jquery AJAX and then submit form in MVC?

Examples related to asp.net-web-api

Entity Framework Core: A second operation started on this context before a previous operation completed FromBody string parameter is giving null How to read request body in an asp.net core webapi controller? JWT authentication for ASP.NET Web API Token based authentication in Web API without any user interface Web API optional parameters How do I get the raw request body from the Request.Content object using .net 4 api endpoint How to use a client certificate to authenticate and authorize in a Web API HTTP 415 unsupported media type error when calling Web API 2 endpoint The CodeDom provider type "Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider" could not be located

Examples related to http-post

Passing headers with axios POST request How to post raw body data with curl? Send FormData with other field in AngularJS How do I POST a x-www-form-urlencoded request using Fetch? OkHttp Post Body as JSON What is the difference between PUT, POST and PATCH? HTTP Request in Swift with POST method Uploading file using POST request in Node.js Send POST request with JSON data using Volley AngularJS $http-post - convert binary to excel file and download