1

I have the following API, which takes care of updating items in the database:

    [Route("update")]
    [HttpPost("")]
    public JsonResult UpdateRecords([FromBody]ICollection<ShoppingItemViewModel> vm)
    {
        if (ModelState.IsValid)
        {
            try
            {
                var items = Mapper.Map<IEnumerable<ShoppingItem>>(vm);

                //update database
                _repository.UpdateValues(items, User.Identity.Name);

                return Json(null);
            }
            catch (Exception Ex)
            {
                Response.StatusCode = (int)HttpStatusCode.BadRequest;
                return Json(null);
            }
        }
        else
        {
            Response.StatusCode = (int)HttpStatusCode.BadRequest;
            return Json(null);
        }
    }

Then under my Angular code I am executing this POST method like following:

    $scope.SaveChanges = function () {
        $http.post("/api/items/update", $scope.items)
            .then(function (response) {
            }, function (err) {
                $scope.errorMessage = "Error occured: " + err;
            }).finally(function () {

            });

    };

What I would like to do, is to introduce new parameters to my initial UpdateRecords function, where some of them are optional. Then depending on the inserted parameters my procedure would do different things.

What I have tried to do is to change my function like following (example):

public JsonResult UpdateRecords([FromBody]ICollection<ShoppingItemViewModel> vm, [FromBody]bool EraseOldItems)

and under my Angular App:

$http.post("/api/items/update", {vm:$scope.items, EraseOldItems: true})

or even

$http.post("/api/items/update", {'vm':$scope.items, 'EraseOldItems': true})

but I could not get the code to work (my parameters were all the time null).

What am I doing wrong here?

1 Answer 1

2

From Parameter Binding in ASP.NET Web API:

At most one parameter is allowed to read from the message body.

// Caution: Will not work!    
public HttpResponseMessage Post([FromBody] int id, [FromBody] string name) { ... }

The reason for this rule is that the request body might be stored in a non-buffered stream that can only be read once.

You can pass a request object that contains other objects:

public class Request
{
    public ICollection<ShoppingItemViewModel> vm { get; set; }
    public bool eraseOldItems { get; set; }
}

And then your action:

[Route("update")]
[HttpPost("")]
public JsonResult UpdateRecords([FromBody]Request request){ ... }
Sign up to request clarification or add additional context in comments.

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.