DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations

Trending

  • How to Submit a Post to DZone
  • How to LINQ Between Java and SQL With JPAStreamer
  • An Overview of Kubernetes Security Projects at KubeCon Europe 2023
  • Extending Java APIs: Add Missing Features Without the Hassle
  1. DZone
  2. Coding
  3. Frameworks
  4. Building a List With ASP.NET Core

Building a List With ASP.NET Core

Paul Michaels user avatar by
Paul Michaels
·
Dec. 12, 19 · Tutorial
Like (3)
Save
Tweet
Share
30.67K Views

Join the DZone community and get the full member experience.

Join For Free

list-on-pavement

I’ve recently been working with ASP.NET Core to build some functionality involving building a list of values. Typically, with ASP.NET  Core using Razor, you have a form that may look something like this:

@using (Html.BeginForm("MyAction", "ControllerName", FormMethod.Post)
{
    @Html.AntiForgeryToken()
    <div class="form-group">
        @Html.LabelFor(model => model.MyValue)
        @Html.TextBoxFor(model => model.MyValue)
    </div>

    <div class="form-group">
        <button type="submit">Submit</button>
    </div>


This works really well in 90% of cases, where you want the user to enter a value and submit. This is your average CRUD application; however, what happens if, for some reason, you need to manipulate one of these values? Let’s say, for example, that you want to submit a list of values.

For the sake of simplicity, we’ll say that the controller accepts a CSV, but we want to build this up before submission. You can’t simply call a controller method for two reasons: the first is that the controller will reload the page; the second is that you don’t have anywhere to put the value on the server. If this was, say, a method to create an entry in a database, the database entry, by definition, couldn’t exist until after the submission.

This all means that you would need to build this list on the client.

You may also like: Blazor Form Validation.

A Solution

Let’s start with a very simple little feature of Html Helpers — the hidden field:

@Html.HiddenFor(model => model.MyList)


This means that we can store the value being submitted to the user, without showing it to the user.

We’ll now need to display the data being added. An easy way to do this is a very simple table. (You can load existing values into the table for editing scenarios):

    <div>
        <table id="listTable">
            <tbody>
                @if ((Model?.ValueList ?? null) != null)
                {
                    @foreach (var v in Model.ValueList)
                    {
                        <tr>
                            <td>@v</td>
                        </tr>
                    }
                }
            </tbody>
        </table>
    </div>    


Pay particular attention to the Table Id and the fact that the conditional check is inside the tbody tag. Now, let’s allow the user to add a new piece of data:

    <div class="form-group">
        @Html.LabelFor(model => model.NewValue)
        @Html.TextBoxFor(model => model.NewValue)
    </div>
    <div>
        <button type="button" id="add-value">Add Value</button>
    </div>


Okay, so now we have a button and a field to add the value; we also have a method of displaying those values. We’ll need a little bit of Javascript (JQuery in this case) to append to our list:

@section Scripts {
        $('#add-value').click(() => {

            const hiddenList = $('#MyList');
            const newValue = $('#NewValue');

            if (!hiddenList.val()) {
                hiddenList.val(newValue.val());
            } else {
                hiddenList.val(hiddenList.val() + ',' + newValue.val());
            }

            $('#listTable > tbody:last-child').append('<tr><td>' + newValue.val() + '</td></tr>');            
        });


On the button click, we get the hidden list and the new value. We then simply add the new value to the list. Finally, we manipulate the table in order to display the new value. If you F12 the page, you’ll notice that the Razor engine replaces the Html Helpers with controls that have Ids that are the same as the fields that they are displaying. (Note: that if the field name contains a “.” as in  MyClass.MyField, the Id would be MyClass_MyField).

When you now submit this, you’ll see that the hidden field contains the correct list of values.

References

  • https://stackoverflow.com/questions/16174465/how-do-i-update-a-model-value-in-javascript-in-a-razor-view/16174926.
  • https://stackoverflow.com/questions/171027/add-table-row-in-jquery.
  • .https://stackoverflow.com/questions/36317362/how-to-add-an-item-to-a-list-in-a-viewmodel-using-razor-and-net-core.


Further Reading

  • 5 .NET Blogs for C# Developers to Follow in 2019.
  • Backend Web API With C#: Step-by-Step Tutorial.
  • Blazor: Running C# in the Browser Using Web Assembly.
ASP.NET ASP.NET Core

Opinions expressed by DZone contributors are their own.

Trending

  • How to Submit a Post to DZone
  • How to LINQ Between Java and SQL With JPAStreamer
  • An Overview of Kubernetes Security Projects at KubeCon Europe 2023
  • Extending Java APIs: Add Missing Features Without the Hassle

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com

Let's be friends: