简体   繁体   中英

Model binding a form created from configurations in ASP.NET Core Razor Pages/MVC

In my database I have configured fields for a product:

Here is what the entity looks like:

ProductField
Id (PK)
ProductId (FK)
Label (To be used as the field label)
Type (Text, TextArea)

When the page loads I have a Page Model for my Product Entity which has a navigation property called Fields of type ProductField. In my razor syntax I am doing the following:

<form method="post">
    @{
        int i = 0;

        if (Model.Product.Fields.Count > 0)
        {
            @foreach (var field in Model.Product.Fields)
            {
                if (field.Type == "Text")
                {
                    <input id="txt_@i" type="text">
                }
                else if (field.Type == "Signature")
                {
                    <textarea id="txtArea_@i"></textarea>
                }
                i++;
            }
        }
    }
</form>

The part that I am having trouble with is creating a ViewModel that can be posted to properly so I can access the value of each field and store it in the database.

There is another table in the database to store the value for each field:

ProductFieldValue
ProductFieldId (FK)
UserId (the Id of the user filling out the form)
Value (value for that field)

What is the proper way to to model binding in a scenario like this using Razor Pages or MVC?

To model binding with List of data in Razor Pages, you need to use name property to pass all data to backend.

In PageModel,declare List to store input data

[BindProperty]
public List<string> DataStored { get; set; }

In razor View

<form method="post">
@{
    int i = 0;

    if (Model.Product.Fields.Count > 0)
    {
        @foreach (var field in Model.Product.Fields)
        {
            if (field.Type == "Text")
            {
                <input type="text" id="txt_@i" class="items" name="DataStored[@i]" />

            }
            else if (field.Type == "Signature")
            {
                <textarea id="txtArea_@i" class="items" name="DataStored[@i]" ></textarea>

            }
            i++;
        }
    }
}

If you use MVC,then accept List as action parameters.

[HttpPost]
public IActionResult Create(List<string> dataStored)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM