POST a form array without successful
You need to generate the controls for the collection in a for
loop so they are correctly named with indexers (note that property BatchProducts
needs to be IList<BatchProductViewModel>
@using (Html.BeginForm("Save", "ConnectBatchProduct", FormMethod.Post))
{
....
<table>
....
@for(int i = 0; i < Model.BatchProducts.Count; i++)
{
<tr>
<td>@Html.TextBoxFor(m => m.BatchProducts[i].Quantity)</td>
<td>@Html.TextBoxFor(m => m.BatchProducts[i].BatchName)</td>
<td>
// add the following to allow for dynamically deleting items in the view
<input type="hidden" name="BatchProducts.Index" value="@i" />
<a class="deleteRow"></a>
</td>
</tr>
}
....
</table>
....
}
Then the POST method needs to be
public ActionResult Save(ConnectBatchProductViewModel model)
{
....
}
Edit
Note: Further to your edit, if you want to dynamically add and remove BatchProductViewModel
items in he view, you will need to use the BeginCollectionItem
helper or a html template as discussed in this answer
The template to dynamically add new items would be
<div id="NewBatchProduct" style="display:none">
<tr>
<td><input type="text" name="BatchProducts[#].Quantity" value /></td>
<td><input type="text" name="BatchProducts[#].BatchName" value /></td>
<td>
<input type="hidden" name="BatchProducts.Index" value ="%"/>
<a class="deleteRow"></a>
</td>
</tr>
</div>
Note the dummy indexers and the non-matching value for the hidden input prevents this template posting back.
Then the script to add a new BatchProducts
would be
$("#addrow").click(function() {
var index = (new Date()).getTime(); // unique indexer
var clone = $('#NewBatchProduct').clone(); // clone the BatchProducts item
// Update the index of the clone
clone.html($(clone).html().replace(/\[#\]/g, '[' + index + ']'));
clone.html($(clone).html().replace(/"%"/g, '"' + index + '"'));
$("table.order-list").append(clone.html());
});
formArray without using ngfor
You are mapping wrong formGroupName
like 1
and 2
instead of 0
and 1
.
And one more thing is that you are adding only item in your form array.
app.component.ts
constructor(private fb: FormBuilder) {
this.form = fb.group({
name: [],
address: fb.array([this.addressGroup()])
})
this.add();
}
add() {
let values = this.form.get('address') as FormArray;
values.push(this.addressGroup());
}
app.component.html
<div formGroupName="0">
<div>
street <input formControlName="street">
</div>
<div>
city <input formControlName="city">
</div>
</div>
<div formGroupName="1">
<div>
street <input formControlName="street">
</div>
<div>
city <input formControlName="city">
</div>
</div>
Reference: https://stackblitz.com/edit/angular-forms-formarray-example-7stqcq?file=src%2Fapp%2Fapp.component.html
formArray - Cannot find path to array of arrays
You can try below html:
<form [formGroup]="myForm" (ngSubmit)="onSubmit()">
<div formArrayName="arr" *ngFor="let a of arr.controls; let i = index"> <!-- arr getter is called -->
<div [formGroupName]="i" style="margin-bottom: 10px;">
<input type="text" name="name" formControlName="name">
<label for="pay">Pay:</label>
<input type="text" name="pay" formControlName="pay">
<div formArrayName="scores"> <!-- Property binding is not required -->
<div *ngFor="let _ of scores(i).controls; let g = index"> <!-- inner FormArray is retrieved based on index -->
<input type="text" [formControlName]="g">
</div></div></div></div>
<button type="submit">Submit</button>
</form>
and define appropriate getter and method to get hold of the FormArray as:
// returns the outer FormArray
get arr(): FormArray {
return this.myForm.get('arr') as FormArray;
}
// returns the inner FormArray based on the index
scores(index: number): FormArray {
return this.arr.at(index).get('scores') as FormArray;
}
Angular FormArray
The main problem is that your "divs" are closed wrong. In this stackblitz I ordered the div of your .html.
NOTE 1: You can use formGroupName="first"
and formGroupName="second"
instead of [formGroup]="bankFormGroup"
and [formGroup]="backForm2Group"
NOTE2: You can use the way form.get('formgroupname.formControlName') in your *ngIf,e.g.
<div *ngIf="form.get('second.property21')?.invalid>...</div>
NOTE3:I like more that the formArrayName="third" was in the <ul>
instead of the <li>
with the *ngFor (but it is a personal opinion)
NOTE4: For me is strange in the .html that you show the inputs "property 1.1" (from the formGroup "first") and "property 1.2" (from the formGroup "second"), and the last input the input "property 1.2" (from the formGroup "first")
Submit Form Array Via AJAX
You could try using :
var dataSend = {};
dataSend['one'] = $('#one').val();
dataSend['two'] = $('#two').val();
dataSend['three'] = $('#three').val();
then in the ajax
data: {dataSend:dataSend}
You can gather data in php with json:
$json = json_encode($_POST['dataSend']);
$json = json_decode($json);
print_r($json);
To see output.
Edit:
You can gather data in php like below:
$one = $json->{'one'};
$two = $json->{'two'};
Not able to store dynamic FormArray in FormGroup
You have a few issues. First of all, it is better to move the Input which adds more FormGroup
s to your FormArray
outside of the <div formArrayName="manager_formArray">
- element. I created a new FormControl this.mgrNameInput = new FormControl('');
for this reason (see StackBlitz for more details).
You also need to add the message to the new entry when you press the Add
-button, calling the addPM()
-method:
addPM(){ // removed the argument, using the controller inside the method instead.
this.manager_formArray.push(this.formBuilder.group({MgrName:this.mgrNameInput.value}));
this.mgrNameInput.reset(); // reset the input field.
}
I also added the remove-method when removing an entry.
removeMgr(index: number){
this.manager_formArray.removeAt(index);
}
Please check the StackBlitz for the complete example
Related Topics
How to Check If a File Is in Use
Split List into Sublists With Linq
Sending Email Through Gmail Smtp Server With C#
Capture Screenshot of Active Window
Type Checking: Typeof, Gettype, or Is
Watermark/Hint/Placeholder Text in Textbox
How to Read a Text File Reversely With Iterator in C#
Good or Bad Practice For Dialogs in Wpf With Mvvm
Extension Method and Dynamic Object
Post a Form Array Without Successful
How to Add User-Supplied Input to an SQL Statement
How to Turn a C# Object into a Json String in .Net
Passing Objects by Reference or Value in C#
Getting All Types That Implement an Interface
How to Get the Type of T from a Member of a Generic Class or Method
Cannot Convert from List≪Derivedclass≫ to List≪Baseclass≫