Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using BeginForm to post form data to an ASP.NET MVC API controller

Basically, I have an API controller with the following method:

public void Post([FromBody] string value)
{
   Repository.Save(value);
}

I construct my form like this:

@using (Ajax.BeginForm(new AjaxOptions { HttpMethod = "Post", Url = "/api/MyController"}))
{
   <input type="text" name="value" value="" />
   <input type="submit" value="Post" />
}

The request is routed to the controller, but for some reason the value is always null. I've tried with and without the [FromBody] attribute.

I could obviously append a value query string parameter to the URL, but I really want to figure out how to post form data with simple types (as opposed to creating my own DTO type).

Thanks!

like image 465
Ted Nyberg Avatar asked Sep 18 '13 15:09

Ted Nyberg


People also ask

What is @using HTML BeginForm ()) in MVC?

Html. BeginForm is the Html Helper Extension Method that is used for creating and rendering the form in HTML. This method makes your job easier in creating form. Here, is the method to create a form using Html.

How can I get data from Web API in MVC controller?

First of all, create MVC controller class called StudentController in the Controllers folder as shown below. Right click on the Controllers folder > Add.. > select Controller.. Step 2: We need to access Web API in the Index() action method using HttpClient as shown below.


1 Answers

By default, Web API tries to get simple types from the request URI. The FromBody attribute tells Web API to read the value from the request body.

Web API reads the response body at most once, so only one parameter of an action can come from the request body. If you need to get multiple values from the request body, define a complex type.

Second, the client needs to send the value with the following format:

=value

and not like this:

value=foo

So, if you post your data like this $.post('/api/myapicontroller', { "": $('#myinput').val() }); it should work just fine and if you would like to send an array of simple types just send the data like this $.post('/api/myapicontroller', { "": ["update one", "update two", "update three"] });

If you use Fiddler just add =John+Smith to the request body and make sure you have the correct content type like this: Content-Type: application/x-www-form-urlencoded.

like image 108
marcus Avatar answered Oct 04 '22 21:10

marcus