.net 将动态生成的表单输入绑定到viewModel

slsn1g29  于 2023-11-20  发布在  .NET
关注(0)|答案(2)|浏览(124)

所以我一直在用.NET 6开发一个Web应用程序。我有一个表单,它有一个按钮,可以根据用户的需要生成尽可能多的输入行。我试图将它与视图模型绑定。

@model IEnumerable<AddToMealViewModel>

<button class="btn btn-success" onclick="addMore()">Add more</button>
<form method="post">
    <div class="wrapper">
        <div class="row-fluid">
            <div>
                @Html.DropDownListFor(m => m.SelectedMealId,
                         new SelectList(Model.Meals, "Id", "Name"),
                         "Select")
                @Html.DropDownListFor(m => m.SelectedProductId,
                         new SelectList(Model.Products, "Id", "Name"),
                         "Select")
                <input asp-for="@Model.Amount" />
            </div>
        </div>
    </div>
    <button type="submit" class="btn btn-primary">Add</button>
</form>
<script>
    function addMore() {
        $(".row-fluid:last").clone().appendTo(".wrapper");
    }
</script>

字符串
问题是,我不知道如何自动将新生成的字段绑定到ViewModel并传递给我的Controller。

bttbmeg0

bttbmeg01#

要动态生成输入行并将其绑定到视图模型,可以尝试以下步骤:

在剃刀视图

@model IEnumerable<AddToMealViewModel>

<button class="btn btn-success" onclick="addMore()">Add more</button>
<form method="post">
    <div class="wrapper">
        @for (var i = 0; i < Model.Count(); i++)
        {
            <div class="row-fluid">
                <div>
                    @Html.DropDownListFor(m => Model.ElementAt(i).SelectedMealId, new SelectList(Model.ElementAt(i).Meals, "Value", "Text"), "Select")
                    @Html.DropDownListFor(m => Model.ElementAt(i).SelectedProductId, new SelectList(Model.ElementAt(i).Products, "Value", "Text"), "Select")
                    <input asp-for="Model.ElementAt(i).Amount" />
                </div>
            </div>
        }
    </div>
    <button type="submit" class="btn btn-primary">Add</button>
</form>
<script>
    var index = @Model.Count();
    function addMore() {
        var newRow = $(".row-fluid:last").clone();
        newRow.find(':input').val(''); // Clear input values
        newRow.find('select').prop('selectedIndex', 0); // Reset dropdowns
        newRow.find(':input').each(function () {
            var name = $(this).attr('name').replace(`[${index - 1}]`, `[${index}]`);
            $(this).attr('name', name);
        });
        newRow.appendTo(".wrapper");
        index++;
    }
</script>

字符串

控制器中

[HttpPost]
public IActionResult YourAction(IFormCollection form)
{
    // var dynamicColumn1= form["dynamicColumn1"];
    // etc.
}

xj3cbfub

xj3cbfub2#

由于我在将结果绑定到模型时遇到了问题,我在下面发布了最终的解决方案。如果有人发现任何改进,请分享。

public IActionResult AddToMeal(IFormCollection form)
        {
            List<AddToMealViewModel> ingredients = MapAddViewModelFromFormCollection(form); 
            return RedirectToAction("Today"); 
        }

        private List<AddToMealViewModel> MapAddViewModelFromFormCollection(IFormCollection form)
        {
            List<AddToMealViewModel> ingredients = new List<AddToMealViewModel>();
            int numberOfLines = form.First().Value.Count - 1;
            for (int i = 0; i <= numberOfLines; i++)
            {
                ingredients.Add(new AddToMealViewModel());
            }

            foreach (var item in form)
            {
                if (nameof(AddToMealViewModel.SelectedMealId) == item.Key)
                {
                    for (int i = 0; i < item.Value.Count; i++)
                    {
                        string? value = item.Value[i];
                        var viewModel = ingredients.ElementAt(i);
                        viewModel.SelectedMealId = int.Parse(value);
                    }
                }
                if (nameof(AddToMealViewModel.Amount) == item.Key)
                {
                    for (int i = 0; i < item.Value.Count; i++)
                    {
                        string? value = item.Value[i];
                        var viewModel = ingredients.ElementAt(i);
                        viewModel.Amount = int.Parse(value);
                    }
                }
                if (nameof(AddToMealViewModel.SelectedProductId) == item.Key)
                {
                    for (int i = 0; i < item.Value.Count; i++)
                    {
                        string? value = item.Value[i];
                        var viewModel = ingredients.ElementAt(i);
                        viewModel.SelectedProductId = int.Parse(value);
                    }
                }
            }
            return ingredients; 
        }

字符串

相关问题