Trouble with IFormCollection not retrieving individual form data

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.

Answer №1

If you come across a similar issue, I encountered a problem that I couldn't resolve, so I decided to try a different approach. I changed the type of my variable (DynamicFormFields) from IFormCollection to string, and from the client side, I now send a JSON string.

The JavaScript code I implemented looks something like this:

<script>
function SubmitForm() {
    var firstName = $('#FirstName').val();
    var dynamicFormFields = JSON.stringify($('#dynamicFormFields').serializeArray());
    $.ajax({
        type: 'POST',
        url: <API URL>,
        data: {
            FirstName: firstName,
            DynamicFormFields: dynamicFormFields
        },
        dataType: "json",   
    }).done(function (result) {
        if (!result.status) {
            alert("Error");
        }
        alert("Success");
    });
}
</script>

On the server side, I am parsing this JSON into key-value pairs like this:

var dynamicFieldList = JsonConvert.
                       DeserializeObject<IEnumerable<DynamicFormKV>>
                       (FormDataVM.DynamicFormFields);

.

/** Key-Value model for parsing dynamic form fields JSON **/

public class DynamicFormKV
{
    public string name { get; set; }
    public string value { get; set; }
}

/******/

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

A new value was replaced when assigning a JSON value inside a loop

Is there a way to generate a structure similar to this? { "drink": { "2": { "name": "coke", "type": "drink" }, "3": { "name": "coke", "type": "drink" } }, "food": ...

Troubleshooting drag-and-drop functionality in a JavaScript HTML5 application resembling a Gmail upload interface

Here is a snapshot of my user interface: Each node in the tree structure is represented by an <li> element along with an <a> link. Furthermore, each folder serves as a dropzone for file uploads similar to the drag-and-drop feature found in Gm ...

Discovering if an array includes a particular value in JavaScript/jQuery

Is there a way to check if the list with the class .sidebar contains an item with data-id="1"? <ul class="sidebar"> <li data-id="1">Option 1</li> <li data-id="2"> Option 2</li> <li data-id="3"> Option 3</li&g ...

Using VueJs, create a dynamic css class name to be applied inline

Can VueJs handle a scenario like this? Html: <div class="someStaticClass {{someDynamicClass}}">...</div> JS: var app = new Vue({ data: { someDynamicClass: 'myClassName' }, mounted: function() { ...

AngularJS redirection causes the previous template to quickly appear and then disappear

This particular question has been circulating without a satisfactory resolution for some time, so hopefully the information provided here will help clear up any confusion. Essentially, I have an object called resolve attached to my routes, set up like thi ...

What is the procedure for adding a JavaScript function to an HTML element that was exclusively created in JavaScript?

I am trying to dynamically change the background color of a row in a table when selecting an object from a dropdown list, but only if the selected number is even. The challenge I am facing is that the objects are created using JavaScript and not directly i ...

Switch between GeoJSON layers by using an HTML button within Mapbox GL JS, instead of relying on traditional links

I am currently developing a web map that requires toggling two GeoJSON layers on and off. In the past, I used Mapbox JS to accomplish this task by adding and removing layers with a custom HTML button click. However, I am facing some challenges in achieving ...

What is the best way to render images on the server side in React?

I've got this snippet of code residing in my server/server.js import path from 'path'; import fs from 'fs'; import React from 'react'; import ReactDOMServer from 'react-dom/server'; import express from 'ex ...

Leveraging the 'passport.isAuthenticated()' method for evaluating numerous user roles within a Node.js application

Below is the code snippet for my custom isAuthenticated function: var isAuthenticated = function (req, res, next) { if (req.isAuthenticated()) return next(); res.redirect('/'); }; Here's a route that uses PassportJs with the custom isA ...

Checking authorization with CognitoUser solely for "code" provided by CognitoUser (npm: amazon-cognito-identity-js)

Currently, I am in the process of implementing the "forget password" feature. However, I have encountered an issue where I would like to verify the "verification code" first before setting a new "password". Unfortunately, the system currently requires bo ...

Retrieve information from api and showcase it in html

Recently, I came across an interesting API file that caught my attention: My goal is to extract information from this API and present it on a HTML page in a visually appealing format. Despite scouring various forums, I have yet to find a solution that fi ...

Utilizing Slick Carousel to dynamically apply animation classes to active slides

I am attempting to focus on the active slide within my slick carousel created by ken wheeler in order to apply an animation to the p element within that slide. Therefore, when the slide is active, the p element will bounce in (or something), and then when ...

Communication between React.js and Node.js in VS Code

I recently started learning React and node js. I managed to create a simple "Hello World" project in reactjs, which works perfectly. App.js import React, { Component } from 'react'; import logo from './logo.svg'; import './App.cs ...

How can I use Java script to find specific text within table rows on a website?

I am looking to create a dynamic table that filters rows based on user input in an input text box. Here is an example table: Row 1: Apples Row 2: Oranges Row 3: Bananas When a user starts typing in the text box, I want the rows to filter accordingly. ...

Encountering a Zone.js error when trying to load an Angular 7 app using ng serve, preventing the application from loading

Scenario: Yesterday, I decided to upgrade my Angular app from version 5.2.9 to 6 and thought it would be a good idea to go all the way to 7 while I was at it. It ended up taking the whole day and required numerous changes to multiple files, mostly due to R ...

When implementing Passport-jwt for fetching user data, req.user may sometimes be undefined

No matter how many answers I search for on Stackoverflow or read through the documentation, I still can't solve my problem. Signing in and signing up works perfectly fine - I have my token. But when I try to fetch my current_user using get('/isAu ...

Using JQuery to properly introduce a script in the body of a webpage

<script> /* adjust #splash-bg height based on #meat element */ $(window).on('load',function(){ var splashbgHeight = $("#meat").css("top"); $("#splash-bg").css("height",splashbgHeight); $(w ...

Is it possible to add a click handler function to a dynamically generated link in Vue?

When working with Vue components, I receive dynamic messages from the server: module.exports = { data() { return: { windowText: '' } }, methods: { showCancelEntrieWindow(){ this.$http.post('/page', {'number& ...

Get a reference to pass as an injection into a child component using Vue js

Is there a way to pass a reference to child components? For example: The Parent component provides the ref: <template> <div ref="myRef" /> </template> <script> export default { name: 'SearchContainer', pr ...

RXJS buffering with intermittent intervals

Situation: I am receiving audio data as an array and need to play it in sequence. The data is coming in continuously, so I am using an observable to handle it. Since the data arrives faster than it can be played, I want to use a buffer to store the data w ...