Utilize a form with a table layout to send all data to an IEnumerable Controller method

I'm experiencing an issue with a form containing data presented in a table structure

@model IEnumerable<myType>
@Html.AntiForgeryToken()
@using (Ajax.BeginForm("Save", "NOC", null, ajaxopts, new { @encType = "multipart/form-data", @id = "myform", @name = "myform" }))
{

<table>
<tr>
<td><input type="hidden" name="myType[0].ID" id="myType[0].ID" value="16" /></td>
<td><input type="text" name="myType[0].Name" id="myType[0].Name" value="Jim" /></td>
<td><input type="checkbox" name="myType[0].Selected" id="myType[0].Selected" checked /></td>
</tr>
<tr>
<td><input type="hidden" name="myType[1].ID" id="myType[1].ID" value="17" /></td>
<td><input type="text" name="myType[1].Name" id="myType[1].Name" value="Bob" /></td>
<td><input type="checkbox" name="myType[1].Selected" id="myType[1].Selected" /></td>
</tr>
</table>
<button id="process" value="Save" class="btn btn-primary">Save</button>
}

When inspecting the Form Data section in Chrome, I can see the list of data that is being sent to the controller....

myType[0].ID: 16
myType[0].Name: Jim
myType[0].Selected: on
myType[1].ID: 17
myType[1].Name: Bob

However, despite this, the controller receives null values.

[HttpPost]
public async Task<ActionResult> SaveData(IEnumerable<myType> model)
{
  return Json("Hi");
} 

In addition, when checking the Preview in Chrome Dev Tools, it displays "Hi" as the response from the Controller.

My JavaScript code is as follows:

$("#process").on("click", function (event){
  event.preventDefault();
  var formData = $("#myForm").serialize();
  $.ajax({
    url: url,
    type: "POST",
    data: formData
  })
});

The 'myType' model is defined as:

public class myType
{
  public int ID { get; set; }
  public string Name { get; set; }
  public bool Selected { get; set; }
}

I am not receiving any JavaScript errors, but unfortunately no data seems to be reaching the controller. Any assistance would be greatly appreciated.

Thank you.

Answer №1

You are creating HTML manually with name attributes that do not correspond to your model. To properly post back to IEnumerable<myType> model, your elements should be like:

<input type="hidden" name="[0].ID />
<input type="hidden" name="[1].ID />

Remove the id attributes as they are invalid and could cause issues with jQuery functions. Using . (dot) in an ID may lead to errors.

Additionally, using a checkbox may not work well because binding a value of on to a boolean value won't function correctly.

It seems like you are generating this HTML dynamically with a JavaScript function based on your comments. I recommend checking out this answer. Initially populate your model with objects and use a for loop to create the correct HTML (ensure the model is IList<myType>)

for(int i = 0; i < Model.Count; i++)
{
  @Html.HiddenFor(m => m.ID)
  @Html.TextBoxFor(m => m.Name)
  @Html.CheckBoxFor(m => m.Selected)
}

Check the generated HTML for correctness.

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

sending a POST request with fetch

When it comes to making AJAX requests, I used to rely on jQuery in the past. However, with the rise of React, there is no longer a need to include the entire jQuery library for this purpose. Instead, it is recommended to use JavaScript's built-in fetc ...

The assignment of ajax success data to variables results in an error because data[0] is not defined

Having some trouble retrieving and assigning data from a database in JavaScript using AJAX to call a PHP script with a MySQL query. Although the AJAX request is successful, when trying to store the data into variables, they appear as undefined or NaN in th ...

Detecting incorrect serialized data entries based on data types

In the scenario where the type MyRequest specifies the requirement of the ID attribute, the function process is still capable of defining a variable of type MyRequest even in the absence of the ID attribute: export type MyRequest = { ID: string, ...

Saving and accessing AJAX XML responses in sessionStorage

I have encountered an issue with storing XML response from ajax into sessionStorage. Despite successfully setting the data, I am unable to retrieve it. $.ajax({ url: '/webservice.svc/getProfile', data: { "memberId": $(authenticat ...

The PKIJS digital signature does not align with the verification process

Explore the code snippet below const data = await Deno.readFile("./README.md"); const certificate = (await loadPEM("./playground/domain.pem"))[0] as Certificate; const privateKey = (await loadPEM("./playground/domain-pk ...

Creating a 404 Error Response in Express.js

Inside app.js, I currently have the following code: // catch 404 and forward to error handler app.use(function(req, res, next) { var err = new Error('Not Found'); err.status = 404; next(err); }); This code executes when a non-existent URL ...

Scrolling seamlessly within a container that is fixed in position

For hours, I've been attempting to incorporate smooth scrolling into my project with no success. The issue lies in the container where the anchor tags are located. If it's set to fixed position or absolute, none of my attempts seem to work. In ...

Use AJAX to send the form instead of using the action attribute

Struggling to get a form to submit using ajax instead of an action attribute, but so far, nothing seems to be working. The PHP script functions correctly when tested with an action submit. I've researched examples, read documentation, asked questions ...

Does the frame take precedence over the button?

const div = document.createElement('div'); // creating a dynamic div element div.setAttribute('id', "layer1"); // setting an id for the div div.className = "top"; // applying a customized CSS class div.style.position = "absolute"; // sp ...

Using Angular 4 to delete selected rows based on user input in typescript

I am facing a challenge with a table that contains rows and checkboxes. There is one main checkbox in the header along with multiple checkboxes for each row. I am now searching for a function that can delete rows from the table when a delete button is clic ...

Unable to find symbol 'Properties'

Currently, I am involved in a .NET Solution that consists of numerous projects. One specific project is named DAL.EF. When navigating to the project properties in Visual Studio 2012 by right-clicking on it, I proceed to the Resources tab located on the lef ...

What is the best way to send an array of objects to a Jade template?

I'm looking to retrieve an array of objects from MongoDB and pass it to the client... Here is an example object: var objeto_img= { name:'name of the file', ...

Getting command line argument parameters in React can be achieved by utilizing the `process.argv`

Is there a way to retrieve command line argument parameters in React? I currently have a React codebase that is utilizing Webpack. When running the following commands - npm run build -- --configuration=dev or npm run build -- --configuration=qa I need t ...

What is the method for configuring body attributes in CSS with AngularJS?

Setting the background image of a page using CSS: body { background: url(http://momentumbooks.com.au/wp-content/uploads/2013/06/space.jpg) no-repeat center center fixed; -webkit-background-size: cover; -moz-background-size: cover; -o-backg ...

Flatbuffers does not exist in this context

Currently, I am working on a nodeJs application that involves the use of Google Flat Buffer. After installing flatc on my MacBook Pro, I compiled the schema below: namespace MyAlcoholist; table Drink { drink_type_name: string; drink_company_name: stri ...

Trim the name property of an object within an object's map function if it exceeds a certain length

Imagine having an object structured like this: var fullObj = { prop1: "myProp1", subobject: { Obj1_id: { id: "Obj3_id", name: "./", otherProperties:... }, Obj2_id: { id: "Obj2_id&q ...

Exploring the potential of utilizing records within deepstream.io

Lately, I've been delving into the world of records and I find myself pondering on the practical limitations when it comes to the size of a json structure. Is there a recommended maximum length? Can you store an entire chat history as an (anonymous) r ...

Launch a non-GUI .NET Framework program even if .NET is not currently installed on the

Can a C# .NET Framework application without GUI be executed on a machine that does not have .NET Framework installed? ...

Using the react-bootstrap library, I have successfully integrated a Navbar

The navigation bar below is not functioning properly, and the container is causing the links to lead to a 404 error page. I have attempted writing it in various formats: <Nav.Link href="" >Name</Nav.Link> <Nav.Link href={"&qu ...

Custom Email Template for Inviting Msgraph Users

I'm currently exploring the possibility of creating an email template for the MS Graph API. I am inviting users to join my Azure platform, but the default email they receive is not very visually appealing. public async sendUserInvite(body: {email: < ...