Using MVC 5 with a Razor (.cshtml) view
You have a list of values in a model that needs to ultimately get data from a control in the view and append them to the list.
For example:
The model contains: public List<string> value { get; set; }
The List is allowed to contain up to 70 values, but can contain less.
In the view you have a button that dynamically adds @Html.editorfor
fields, much like this:
For each new field that is created, it's corresponding value must be appended to the List<string> value
. So in this example,
The user clicks "Add Field", the new text box appears, and he enters "Line 1"
value[0] = "Line 1"
The user clicks "Add Field" again to add another value - he enters "Line 2"
value[1] = "Line 2"
The User can add UP TO 70 fields (i.e He can click "add field" 65 times to add 65 values to the value list)
What would be the quickest and most efficient way to bind the data in this manner?
Before you submit make sure those dynamically added inputs have correct model names and you should be fine. So in your example it would be something similar to this:
<input type="text" name="value[0]" value="Line 1"/>
<input type="text" name="value[1]" value="Line 2"/>
<input type="text" name="value[3]" value="Line 3"/>
And the model binder will automatically create a List of string
with those 3 strings ("Line 1","Line 2","Line 3") in them and assign it to the corresponding property, in this case, value
.
EDIT: Here's how your addField function could look like to do just that:
function addField(){
var addedFieldCount=$('input.dynamic-field').length;
if(addedFieldCount==70){//But you should check it on the server side too.
alert('No more field allowed');
return;
}
$('#fieldContainer').append('<input name="value['+addedFieldCount+']"/>');
}
That's all. If you call it hard coding then go call it.
EDIT2: As Stephen Muecke noted, you do not need indexer when you're dealing with a collection of string
. (I was not aware of that :)). So your function becomes even simpler:
function addField(){
var addedFieldCount=$('input.dynamic-field').length;
if(addedFieldCount==70){//But you should check it on the server side too.
alert('No more field allowed');
return;
}
$('#fieldContainer').append('<input name="value"/>');
}
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