Greetings everyone!
I am binding complex object FullAddress while POSTing data to a Controller.
VIEW:
<fieldset>
<legend>Address</legend>
<div class="form-group">
<div class="col-md-7">
<textarea asp-for="FullAddress.AddressLine" class="form-control"></textarea>
<span asp-validation-for="FullAddress.AddressLine" class="text-danger" />
</div>
<div class="row col-md-3 col-md-offset-1" >
<input asp-for="FullAddress.IsPrimary" checked="checked" type="radio" value="true" class="col-md-1" style="width:5px;" />
<span class="col-md-4">primary</span>
<input type="button" value="+" class="btn btn-sm btn-default col-md-1" style="width:9px;" onclick="addAddressTxtField()">
</div>
</div>
<div id="addresses-to-add"></div>
</fieldset>
MODEL:
public class CreatePersonViewModel
{
public AddressVm FullAddress { get; set; }
}
public class AddressVm {
public string AddressLine { get; set; }
public bool IsPrimary { get; set; }
}
So far so good, everyone's happy. But then, all of the sudden, I append similar chunk of html code into my div using Javascript.
JS:
function addAddressTxtField() {
var html = '<div class="form-group" style="display:none"><div class="col-md-7">'
+ '<textarea class="form-control" name=FullAddress.AddressLine"></textarea>'
+ '<span class="text-danger field-validation-valid" data-valmsg-replace="true" data-valmsg-for="FullAddress.AddressLine"></span>'
+'</div><div class="row col-md-3 col-md-offset-1">'
+ '<input class="col-md-1" type="radio" name="FullAddress.IsPrimary" data-val-required="The IsPrimary field is required." data-val="true" style="width:5px;" value="true">'
+'<span class="col-md-4">primary</span>'
+ '<input class="btn btn-sm btn-default col-md-1" type="button" style="width:9px;" value="-" onclick="removeTextfield(this)"></div></div>'
var newAddressTxtfield = $('#addresses-to-add').append(html);
newAddressTxtfield.children().show('slow'); };
That is resulting having two textareas for the user inputs and two radio buttons. Right? Therefore I am forced to use a collection of my AddressVm models. Something like this:
public IList<AddressVm> AddressList { get; set; }
So this doesn't really fit to my code, because I can't use a for loop to assign the fields. Of course, I can do the ugly stuff - hardcode the brackets and indexes.
Like this:
<textarea asp-for="AddressList[0].AddressLine" class="form-control"></textarea>
<span asp-validation-for="AddressList[0].AddressLine" class="text-danger" />
And later create js variable that will iterate each time the user adds a new input field, but that is not really what I am looking for. Ideally, I would like to use IEnumerable or anything that is equally "clean". What would be the best solution to my problem, that you recommend? Maybe I should use IDictionary or create a custom model binding? Any help would be much appreciated.