动态将字段添加到Razor表单 [英] Dynamically Add Fields to Razor Form

查看:148
本文介绍了动态将字段添加到Razor表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Razor表单,其中包含要动态添加项目的项目列表/表.您可以从下拉菜单中选择项目,然后单击添加",然后下拉菜单中的项目将被添加到列表中.然后,当我提交表单并且控制器的HttpPost方法可以处理输入时,我希望所有这些都通过POST发送.

I have a Razor form with a list/table of items that I'd like to dynamically add items to. You can select the items from a dropdown, click "Add", and the item from the dropdown will be added to the list. I'd then like all of that to be sent via POST when I submit my form and my controller's HttpPost method can handle the input.

有没有一种方法可以动态添加字段,并且仍然能够在HttpPost函数中将它们作为参数接受?

Is there a way to dynamically add fields and still be able to accept them as arguments in the HttpPost function?

推荐答案

第一个答案是正确的,因为您可以遍历表单集合以获取表单元素中动态插入的字段的值.我只是想补充一点,您可以利用 some 的整洁绑定.

The first answer is correct in that you can iterate over a form collection to get the values of the dynamically inserted fields within your form element. I just wanted to add that you can utilize some of the neat binding.

以下代码接受针对该操作发布的文本框的动态列表.在此示例中,每个文本框都具有与dynamicField相同的名称. MVC很好地将它们绑定到字符串数组中.

The code below accepts a dynamic list of textboxes that were posted against the action. Each text box in this example had the same name as dynamicField. MVC nicely binds these into an array of strings.

.NET完整小提琴: https://dotnetfiddle.net/5ckOGu

Full .NET Fiddle: https://dotnetfiddle.net/5ckOGu

示例代码(为清晰起见,片段)动态添加示例字段

            @using (Html.BeginForm())
            {
                @Html.AntiForgeryToken()

                <div id="fields"></div>

                <button>Submit</button>
            }


            <div style="color:blue"><b>Data:</b> @ViewBag.Data</div>

    <script type="text/javascript">

        $(document).ready(function() {
            var $fields = $('#fields');
            $('#btnAddField').click(function(e) {
                e.preventDefault();
                $('<input type="text" name="dynamicField" /><br/>').appendTo($fields);
            });
        });

    </script>

该操作中的示例代码接受了帖子中的动态字段.

    [HttpPost]
    public ActionResult Index(string[] dynamicField)
    {
        ViewBag.Data = string.Join(",", dynamicField ?? new string[] {});
        return View();
    } 

输出屏幕截图

这篇关于动态将字段添加到Razor表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆