ASP.NET Core how to pass List<int> from view to Controller

Viewed 3813

In ASP.NET Core, I have searched around but cannot figure out how to pass a list from the view to controller. I can create a form and pass a single int value, but not a List<int>.Here is what I have to pass a single value

<form id="myForm">
    <div class="modal-body">
        <div class="form-group">
           <label class="custom-label">
           <div class="col-sm-3">
               <input name="singleValue" type="text" class="form-control" />
           </div>
        </div>
        <a href="#" class="btn btn-success" onclick="SaveForm('UpdateFunction', 'ControllerName')">Update</a>
</form>

My controller is

public IActionResult UpdateFunction(int singleValue)
{
    var model = _context.TableName.SingleOrDefault(f => f.Id == singleValue);
    model.Name = "Whatever";
    _context.Update(model);
    _context.SaveChanges();

    return Json(true);
}

However because I would like to update multiple values at a time instead of just int singleValue, I have tried passing

public IActionResult UpdateFunction(int[] list) or public IActionResult UpdateFunction(List<int> list)

into the function parameters. I have tried entering multiple int values into the text box with/without commas, brackets, nothing works and the lists are always empty. My goal is to just pass the list or array to controller, then loop through the values in the list. My question is how can I pass a List<int> to the controller?

3 Answers

Input of type text provides single value. You cannot put a list in it. In you form you have input with name "singleValue".

When the form is posted - model binder mechanism tries to bind form data to params of the action method, which is UpdateFunction in your case.

If you want to use input of type text with the values like "1;2;3" and treat it as a list - better option will be to use javaScript on my opinion. Collect your values form the form, make preprocessing and send the request to the server.

On the other hand - you can construct your viewModel, which has a list in it - myList for example. For each item of the list you create an input via foreach loop. The name of the input should be myList[0], myList[1], myList[2] etc. When you post the form - values, which you have specified in your inputs, will be stored in myList[index] respectively.

Here are your few options:

  1. If you have multiple text inputs to get multiple numbers from user then you can access those using form object like HttpContext.Request.Form[<FieldName>].

  2. You can get multiple values in single text box with a comma or a space separating those. Validation will be a pain, but you can then get the string, chop it in controller and use it.

    public IActionResult UpdateFunction(string multipleValues)
    {
           var ints = multipleValues.Split(new[] { ",", " " }, StringSplitOptions.RemoveEmptyEntries);
    }
    
  3. Use custom object to pass values back. But you have to create json object on client and post back using AJAX (jQuery ?).

    public class ListOfInts
    {
           List<int> Ids{get;set;}
    }
    

in view:

   <script>
          $(function(){
                 $("#btn").click(function(){
                        var o={};
                        o.Ids = [<get values from inputs and];
                        $.ajax({....});
                 });
          });
   </script>

All of these need bit work to actually implement (and I need a coffee), but this will give you an idea.

I think the implementation of the controller has issues. you need to ad [FromBody] tag to get values from the request body.

like

public IActionResult UpdateFunction([FromBody] List<int>myValues)
{
    //Your code here..
}
Related