herme 0
herme 0

Reputation: 972

How to set asp-for in a for loop

I have a for loop to generate fields on a form.

How can I set the value of asp-for based on the current index?

<label asp-for=@("Value" + i) class="control-label"></label> does not work.

Upvotes: 5

Views: 11626

Answers (1)

Anton Toshik
Anton Toshik

Reputation: 2909

You can bind the model with an index like so using ether foreach or for:

@page
@model IndexModel
@{
    ViewData["Title"] = "Home page";
    int i = 0;
}
<form method="post">
    @foreach (var item in Model.Items)
    {

        <input asp-for="Items[i]" />
        i++;
    }

    @for (int j = 0; j < Model.Items.Count; j++)
    {

        <input asp-for="Items[j]" />
    }
    <button type="submit">Submit</button>
</form>

And the code behind:

public class IndexModel : PageModel
{
    [BindProperty]
    public List<string> Items { get; set; }

    public void OnGet()
    {
        Items = new List<string> { "one", "two", "three" };
    }

    public void OnPost(List<string> items)
    {

    }
}

Here is a bit of how it works:

In this controller you have 2 action, one returns a list of strings which will be out model. And the second action will accept a parameter as a list of strings.

[Route("[controller]")]
public class TestController : Controller
{

    [HttpGet("[action]")]
    public IActionResult Test()
    {
        return View(new List<string> { "one", "two", "three" });
    }

    [HttpPost("[action]")]
    public IActionResult Test(List<string> Words)
    {
        return Ok();
    }
}

Now in our Test view Test.cshtml file, we want to display this list of string with their index and when we change these values we want to be able to post them.

@model List<string>

@{
    int i = 0;
}

<form method="post">

    @foreach (var item in Model)
    {
        <label>@item  - @i</label>
        <input name="Words[@i]" value="@item" />

        i++;
    }
    <button type="submit">Submit</button>
</form>

Here is the result:

Result

And after submitting the form, the values in the input fields will appear in the list of strings, because of the html name attribute.

You have to understand that the tag helper asp-for is used by Razor to generate all sorts of html attributes on the field such as name/id/data-* etc... the main thing you need is the name attribute to bind the value.

Upvotes: 8

Related Questions