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?
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With