What is the recommended pattern for binding an array-type property to a form in ASP.NET Core Razor?

Christopher Wright 20 Reputation points
2024-10-04T13:11:19.4633333+00:00

Hi,

I am using ASP.NET Core 8 Razor, and I am trying to figure out what has to be done to transmit a property of type int[] to/from a form as a hidden field. Scalar values are pretty easy (just put BindProperty on a property and use a hidden input field to capture it in the form), but does something like this exist for arrays? Also, I need to support scenarios where it is not known how many elements are going to be passed inside the array.

.NET
.NET
Microsoft Technologies based on the .NET software framework.
3,915 questions
ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,608 questions
0 comments No comments
{count} votes

Accepted answer
  1. AgaveJoe 28,536 Reputation points
    2024-10-04T15:07:47.5766667+00:00

    The common programming pattern is taking advantage of model binding where the input name (html) contains an index.

    https://learn.microsoft.com/en-us/aspnet/core/mvc/models/model-binding?view=aspnetcore-8.0#collections

    @page
    @model RazorPagesDemo.Pages.BindCollectionExModel
    @{
        ViewData["Title"] = "Model Bind a Collection";
    }
    <div>
        <form method="post">
            @for (int i = 0; i < Model.MyArray.Length; i++)
            {
                <input type="hidden" asp-for="MyArray[i]" />
            }
            <input type="submit" value="submit" />
        </form>
    </div>
    <div>
        <ul>
            @foreach (int item in Model.SubmittedValues)
            {
                <li>
                    @item
                </li>
            }
        </ul>
    </div>
    
        public class BindCollectionExModel : PageModel
        {
            public void OnGet()
            {
                //Populate myArray
                MyArray = new int[] { 1, 2, 3, 4, 5 };
            }
            public void OnPost() 
            {
                SubmittedValues.AddRange(MyArray);
            }
            [BindProperty]
            public int[] MyArray { get; set; }
            public List<int> SubmittedValues { get; set; } = new List<int>();
        }
    
    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.