Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically Add Fields to Razor Form

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.

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

like image 997
muttley91 Avatar asked Mar 03 '15 01:03

muttley91


2 Answers

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.

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.

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

Sample code (snippets for clarity) dynamically adding sample fields

            @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>

Sample code from the action accepting the dynamic fields in a post.

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

Screenshot of output

sample screenshot

like image 97
Jason W Avatar answered Nov 16 '22 09:11

Jason W


Every combobox/hiddenfield/textbox/... that is included inside the <form> element gets posted on submit. Doesn't really matter if you create them on-fly or have them ready by default. The biggest difference however is that with those created dynamically you can't really utilize that neat binding we're used to. You'll have to perform validation etc. manually as well.

Then you'll have a method like this:

public ActionResult HandleMyPost(FormCollection form) 
{
    // enumerate through the FormCollection, perform validation etc.
}

FormCollection on MSDN

like image 43
walther Avatar answered Nov 16 '22 08:11

walther