{{announcement.body}}
{{announcement.title}}

Building a List With ASP.NET Core

DZone 's Guide to

Building a List With ASP.NET Core

In this article, we discuss how to use Razor's HTML Helpers in order to better manage user data submitted in a form.

· Web Dev Zone ·
Free Resource

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


Further Reading

Topics:
web dev ,asp.net ,c# ,windows ,blazor ,tutorial

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}