2

I've googled a whole day but still can't find the answer. I need to POST data via jQuery.post to Web API MVC-4 but unable to. This is my routing:

routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);

and this is my Controller (the GET works!):

    public string Get(int id)
    {
        return "value";
    }

    public void Post([FromBody]string data)
    {
        //body...
    }

This is the jQuery.post:

$.post('api/mycontroller', { key1: 'val1' });

Any idea ?

Edit:

@Darin: I tried this:

public class UnitDetails{
    public string id { get; set; }
}

and:

public void Post(UnitDetails id) {
    //body...
}

and:

$.post('api/mycontroller', {id:'string1'});

But still I miss something.. it doesn't stop in Post(...){...}. Again - Get(...){...} does work.. ?

1
  • There are special routes for API controllers, recognizable by MapHttpRoute instead of MapRoute. By default, they're defined in App_Start/WebApiConfig.cs. What does this route configuration look like? Commented Oct 17, 2012 at 11:45

2 Answers 2

6

This is by design and the only way to make this work with a primitive type such as a string is the following:

$.post('/api/mycontroller', '=' + encodeURIComponent('val1'));

So the body of the POST request must contain the following:

=val1

instead of:

data=val1

This has been discussed in this thread.

As an alternative you could define a view model:

public class MyViewModel
{
    public string Data { get; set; }
}

and then have your controller action take this view model as parameter:

public void Post(MyViewModel model)
{
    //body...
}

Contrary to primitive types, complex types use formatters instead of model binding. Here's an article which covers how does the Web API does parameter binding.

Sign up to request clarification or add additional context in comments.

2 Comments

I tried what you suggested (see in the question's edit, above), with no success..
Rename your action parameter to something different than id. For example: public void Post(UnitDetails details) { ... }.
0

You're posting to api/mycontroller. ASP.NET MVC automatically appends the name supplied with 'Controller', so it's looking for a controller named mycontrollerController. The name of your API controller is not mentioned in your post, but I suspect it's not that.

Assuming that your controller is named 'myController', try posting to api/my.

$.post('api/my', { id: 'string1' });

Comments

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.