I have a problem when I try to bind input elements with items of a list. The pages that I have this problem are very complex so I will try to reproduce the problem using a simple razor page with a list of strings. My Razor Page PageModel is the following:
public class TestListModel : PageModel
{
[BindProperty]
public List<string> Titles { get; set; }
public IActionResult OnGet()
{
Titles = new List<string> { "Jan", "Feb", "Mar", "Apr" };
return Page();
}
public IActionResult OnPost()
{
Titles = Titles.OrderBy(m => m).ToList();
return Page();
}
}
I have a Titles property which has a BindProperty attribute. In OnGet method I just add a short list of four strings (the first four months of the year). In OnPost method, I just sort the Titles.
Below you can see the equivalent html.
<form method="post">
@for (int i = 0; i < Model.Titles.Count(); i++)
{
<div class="form-group">
<div>Value in div : @Model.Titles[i]</div>
<input asp-for="Titles[i]" class="form-control" />
</div>
}
<input type="submit" value="Submit" />
</form>
I have a form which contains a loop which displays the value of the element and an input for each element of the list. I also have a submit button in order to post the elements of the list back to server. The OnGet Method generates the following result.
Everything seems to work. For each element we have the value appears as text and one input which contains the value of the element.
Now I click the submit button in order to hit the OnPost method which will sort the data and the updated view is the following:
As you can see the text for each element appears properly. They are sorted the way that we changed the list in the OnPost method but the inputs contain the values that the form submitted instead of having the updated value after sorting the list.
Can someone tell me how to fix the <input asp-for="Titles[i]" class="form-control" />
tag so that it will display the value that the current element actually has?