I've been working on an asp.net core MVC project where I encountered a requirement to add dynamic fields to a view that already has a form with static fields. These dynamic fields are fetched from the database and need to be submitted along with the static fields. To achieve this, I decided to use FormCollections in order to gather the form fields inside the form.
@model FormDataVM
<section>
<form class="staticFormFields">
<input type="text" id="FirstName" value="@Model.FirstName">
</form>
<form class="dynamicFormFields">
@foreach (var field in Model.DynamicFields)
{
<div class="form-group row">
<label class="col-md-4 col-form-label">@field.FieldTitle</label>
<div class="col-md-8">
<input class="form-control" type="@field.FieldType" placeholder="@field.FieldTitle" value="@field.FieldValue" name="@field.FieldCode" />
</div>
</div>
}
</form>
<button type="button" class="btn btn-primary" onclick="SubmitForm">Save</button>
</section>
To handle the dynamic fields in the server side, I added an IFormCollection member to my viewmodel like this:
public class FormDataVM
{
public string FirstName { get; set; }
public IFormCollection DynamicFormFields { get; set; }
}
On button click, I send an Ajax call to the API like this:
<script>
function SubmitForm() {
var firstName = $('#FirstName').val();
var dynamicFormFields = $('#dynamicFormFields').serialize();;
$.ajax({
type: 'POST',
url: <API URL>,
data: {
FirstName: ,
DynamicFormFields: dynamicFormFields
},
dataType: "json",
}).done(function (result) {
if (!result.status) {
alert("Error");
}
alert("Success");
});
}
}
</script>
However, I noticed that the DynamicFormFields variable contained all the fields data (both static and dynamic) instead of just the dynamic fields. This behavior puzzled me and I'm seeking guidance on why this is happening and the correct approach to handle this situation.
Any help would be greatly appreciated.