Creating List of Input Using Model and HtmlHelper

Kmcnet 1,066 Reputation points
2024-11-01T15:37:44.67+00:00

Hello everyone and thanks for the help in advance. I want to create a from that utilizes a list of input text boxes that corresponds with a model of a database table. The controller accepting the input expects a List<tblData> which in turn utilizes Entity Framework to insert the range. If I understand correctly, the html will need to look like:

<input type="text" id="tblData[0].InputName" name="tblData[0].InputName" />
<input type="text" id="tblData[1].InputName" name="tblData[1].InputName" />
<input type="text" id="tblData[2].InputName" name="tblData[2].InputName" />

Is there a simple way to create this html structure using a model and Html Helper, or do I need to create this using basic html? Any help would be appreciated.

Developer technologies | ASP.NET | ASP.NET Core
{count} votes

2 answers

Sort by: Most helpful
  1. SurferOnWww 4,711 Reputation points
    2024-11-02T02:24:29.1333333+00:00

    Is there a simple way to create this html structure using a model and Html Helper ASP.NET Core MVC. .NET 8.0. Never used tag helper.

    Please refer to the following sample which properly indexes the name attribute of input element:

    Model

    The Country class below assumes the tblData class in your question.

    namespace MvcNet8App.Models
    {
        public class Country
        {
            public string? Name { get; set; }
            public string? Capital { get; set; }
            public string? Continent { get; set; }
        }
    }
    

    Controller

    using Microsoft.AspNetCore.Mvc;
    using MvcNet8App.Models;
    
    namespace MvcNet8App.Controllers
    {
        public class CollectionController : Controller
        {        
            public IActionResult Index()
            {
                return View();
            }
            
            public IActionResult Edit(int id)
            {
                var countries = new List<Country>
                {
                    new Country { Name = "Italy", Capital = "Rome", Continent = "Europe" },
                    new Country { Name = "Spain", Capital = "Madrid", Continent = "Europe"},
                    new Country { Name = "USA", Capital = "Washington", Continent = "NorthAmerica"}
                };
    
                return View(countries);
            }
    
            [HttpPost]
            [ValidateAntiForgeryToken]
            public IActionResult Edit(List<Country> countries)
            {
                if (ModelState.IsValid)
                {
                    return RedirectToAction(nameof(Index));
                }
    
                return View(countries);
            }
        }    
    }
    

    View

    @model IList<MvcNet8App.Models.Country>
    
    @{
        ViewData["Title"] = "Edit";
    }
    
    <h1>Edit</h1>
    
    <hr />
    <div class="row">
        <div class="col-md-4">
            <form asp-action="Edit">
                @for (int i = 0; i < Model.Count; i++)
                {
                    <div class="form-group">
                        @Html.LabelFor(m => m[i].Name)
                        @Html.EditorFor(m => m[i].Name)
                    </div>
                    <div class="form-group">
                        @Html.LabelFor(m => m[i].Capital)
                        @Html.EditorFor(m => m[i].Capital)
                    </div>
                    <div class="form-group">
                        @Html.LabelFor(m => m[i].Continent)
                        @Html.EditorFor(m => m[i].Continent)
                    </div>
                    <hr />
                }
                <div class="form-group">
                    <input type="submit" value="Save" class="btn btn-primary" />
                </div>
            </form>
        </div>
    </div>
    
    @section Scripts {
        @{
            await Html.RenderPartialAsync("_ValidationScriptsPartial");
        }
    }
    

    html code rendered by View

    <div class="row">
        <div class="col-md-4">
            <form action="/Collection/Edit" method="post">
                    <div class="form-group">
                        <label for="z0__Name">Name</label>
                        <input class="text-box single-line" id="z0__Name" name="[0].Name" type="text" value="Italy" />
                    </div>
                    <div class="form-group">
                        <label for="z0__Capital">Capital</label>
                        <input class="text-box single-line" id="z0__Capital" name="[0].Capital" type="text" value="Rome" />
                    </div>
                    <div class="form-group">
                        <label for="z0__Continent">Continent</label>
                        <input class="text-box single-line" id="z0__Continent" name="[0].Continent" type="text" value="Europe" />
                    </div>
                    <hr />
                    <div class="form-group">
                        <label for="z1__Name">Name</label>
                        <input class="text-box single-line" id="z1__Name" name="[1].Name" type="text" value="Spain" />
                    </div>
                    <div class="form-group">
                        <label for="z1__Capital">Capital</label>
                        <input class="text-box single-line" id="z1__Capital" name="[1].Capital" type="text" value="Madrid" />
                    </div>
                    <div class="form-group">
                        <label for="z1__Continent">Continent</label>
                        <input class="text-box single-line" id="z1__Continent" name="[1].Continent" type="text" value="Europe" />
                    </div>
                    <hr />
                    <div class="form-group">
                        <label for="z2__Name">Name</label>
                        <input class="text-box single-line" id="z2__Name" name="[2].Name" type="text" value="USA" />
                    </div>
                    <div class="form-group">
                        <label for="z2__Capital">Capital</label>
                        <input class="text-box single-line" id="z2__Capital" name="[2].Capital" type="text" value="Washington" />
                    </div>
                    <div class="form-group">
                        <label for="z2__Continent">Continent</label>
                        <input class="text-box single-line" id="z2__Continent" name="[2].Continent" type="text" value="NorthAmerica" />
                    </div>
                    <hr />
                <div class="form-group">
                    <input type="submit" value="Save" class="btn btn-primary" />
                </div>
            <input name="__RequestVerificationToken" type="hidden" value="CfDJ8K9TttPMA5pPkueYr6bUiHuFZY7NJSip5auaseK5C-chks5XsqlUDKTeG_i-enQsk3Pz-Vi0VAPZbUJxjJWWVbT-txov3DYj-8hiIFsmltlvKIDeHkOtp-ydZXXG0kthArcget-GlW1jj6AfONiN9Qw" /></form>
        </div>
    </div>
    

    Result of model binding

    enter image description here

    0 comments No comments

  2. Anonymous
    2024-11-04T04:52:05.8066667+00:00

    Hi Kmcnet

    No matter using Html Helper or Tag Helper can achieve your requirement. In ASP.NET Core, I recommend you use Tag Helper.They are more intuitive, blend well with HTML syntax, and are designed to work seamlessly in ASP.NET Core.

    The importance is to use for loop, asp-for generates the id and name HTML attributes.:

    @model MyFormViewModel
    <form asp-action="Create" method="post">
        @for (int i = 0; i < Model.tblDataList.Count; i++)
        {
            <div>
                <label asp-for="@Model.tblDataList[i].InputName">Input @i</label>
                <input asp-for="@Model.tblDataList[i].InputName" class="form-control" />
                <span asp-validation-for="@Model.tblDataList[i].InputName" class="text-danger"></span>
            </div>
        }
        <button type="submit">Submit</button>
    </form>
    

    Be sure import the namespace in current view or globally import in _ViewImports.cshtml:

    @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
    

    Model design:

    public class tblData 
    { 
        public string InputName { get; set; } 
    }
    public class MyFormViewModel
    {
        public List<tblData> tblDataList { get; set; } = new List<tblData>();
    }
    

    Reference:

    Tag Helpers in ASP.NET Core

    Tag Helpers in forms in ASP.NET Core especially The Input Tag Helper


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best regards,
    Rena

    0 comments No comments

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.