Golide
Golide

Reputation: 999

Passing variables to IHttpActionResult Methods

I want to consume WebApi in android as below (in NewProductActivity.java):

     protected String doInBackground(String... params) {
        List<NameValuePair> args = new ArrayList<NameValuePair>();
        args.add(new BasicNameValuePair("name", editTextName.getText().toString()));
        args.add(new BasicNameValuePair("price", editTextPrice.getText().toString()));
        args.add(new BasicNameValuePair("description", editTextDescription.getText().toString()));
        JSONHttpClient jsonHttpClient = new JSONHttpClient();
        Product product = (Product) jsonHttpClient.PostParams(ServiceUrl.PRODUCT, args, Product.class);
        Intent intent = new Intent(getApplicationContext(), MainActivity.class);
        startActivity(intent);
        finish();
        return null;
    }

In my Web api i assigned variables to parameters in ProductsController.cs as below:

    [HttpPost]
    //[ResponseType(typeof(Product))]
    public IHttpActionResult InsertProduct(string name, decimal price, string description)
    {
        Product product = new Product()
        {
            Name = name,
            Price = price,
            Description = description
        };
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        db.Products.Add(product);
        db.SaveChangesAsync();

        return Ok(product.ID);
    }

When i test my api for POST in Fiddler i am getting a 405 status code.I have tried using:

    //[Route("api/products/{name}/{price}/{description}")]
    // POST: api/Products
    [HttpPost]
    //[ResponseType(typeof(Product))]
    public IHttpActionResult PostProduct(string name, decimal price, string description)
    {

as well as the original implementation from the example im following (http://hintdesk.com/how-to-call-asp-net-web-api-service-from-android) but i still get a 405:

     [HttpPost]
    //[ResponseType(typeof(Product))]
    public Product Post(string name, decimal price, string description)
    {
        Product product = new Product()
        {
            Name = name,
            Price = price,
            Description = description
        };

Upvotes: 0

Views: 825

Answers (1)

Vlado Pandžić
Vlado Pandžić

Reputation: 5058

If you want to POST to MVC controller I would do this:

Make complex model (class) with your properties like this:

class MyRequest{

public string name {get;set};
public  decimal price{get;set};

public  string description{get;set};
}

and change your controller like this:

  public Product Post(MyRequest request)

Don't forget to change your android code so that it sends complex object.

Upvotes: 0

Related Questions