Click here to Skip to main content
15,887,027 members
Articles / Web Development / HTML
Tip/Trick

How to Post HTML Table Rows as a List/Array to MVC Controller

Rate me:
Please Sign up or sign in to vote.
4.86/5 (14 votes)
17 Jun 2015CPOL2 min read 91.1K   1.9K   12   5
In this tip, I describe how to post/send data of a table (or list) of HTML for a LIST/ARRAY in C#.

Introduction

This tip describes how to post a data list (table, ul/li, etc.) to a MVC controller as an Array/List in C#.
I demonstrate how to add rows to a table in HTML to your view and subsequently receive the rows added as parameter of the Controller. This makes it possible to receive a list created dynamically as a Post in your Controller.

Below, I will explain step-by-step how to create a Web project with a sample page. Create 2 classes that represent the data and the JavaScript necessary to post a list.

Background

I did some search on the internet and had trouble finding an article detailing how to post without using JSON, just posting the data needed. In my opinion, this was the simplest way to do. The approach below basically adds hidden fields to the form before you submit it. So the ASP.NET MVC is able to receive the list of added items in the table. I used 2 ways in the examples for download: post the data through a "submit" button common. And post the data by using $. ajax. Below are the details of how I created and explained some decisions.

Using the Code

Initially, I created a project Web Application with C# without authentication. Put the name you want (it is irrelevant in this example) and Add a folder Models to the project.

Now right-click the folder newly created Model. Add a new class named ModelNomeTel with the code:

C#
public class ModelNomeTel
{
    public string Nome { get; set; }
    public string Telefone { get; set; }
}

Repeat the process by adding a new class called ModelRecebe with the code:

C#
public class ModelRecebe
{
	public List<ModelNomeTel> NomeTels { get; set; }
}

OK. We have classes that should receive the post with the data added to a table. We also need a View. In Solution Explorer, add a View called PostTable.cshtml inside the Home folder.

HTML
@{
Layout = "~/Views/Shared/_Layout.cshtml";
}

@using (Html.BeginForm("PostTable", "Home", FormMethod.Post, new { @id = "formPost" }))
{
	<div class="row">
		<div class="col-sm-6">
			<div class="form form-horizontal">
				<div class="form-group">
					<label>Nome:</label>
					<input type="text" id="textNome" class="form-control" />
				</div>
				<div class="form-group">
					<label>Telefone:</label>
					<input type="text" id="textTel" class="form-control" />
				</div>
				<div class="form-group">
					<label>&nbsp;</label>
					<button id="buttonAdicionar" type="button" 
					class="btn btn-primary">Adicionar</button>
				</div>
			</div>
	</div>
	<div class="col-sm-6">
		<div class="form-horizontal">
			<table id="tablePost" class="table table-bordered table-striped">
				<thead>
					<tr>
						<th>Nome</th>
						<th>Telefone</th>
					</tr>
				</thead>
				<tbody></tbody>
			</table>
			<div class="form-group">
				<label>&nbsp;</label>
				<button id="buttonPost" type="submit" 
				class="btn btn-primary">Postar</button>
			</div>
		</div>
	</div>
</div>
}

@section scripts{
<script type="text/javascript">
	$(document).ready(function () {
		$("#buttonAdicionar").on("click", function () {
			var nome = $("#textNome").val();
			var tel = $("#textTel").val();
	
			$("#tablePost > tbody").append("<tr data-nome='" + 
			nome + "' data-tel='"+ tel +"'><td>" + 
			nome + "</td><td>" + tel + "</td></tr>");
			
			$("#textNome").val('');
			$("#textTel").val('');
			
			$("#textNome").focus();
		});

		$("#buttonPost").on("click", function () {
			var listName = "NomeTels";
			
			var qtd = 0;
			$("#tablePost > tbody > tr").each(function () {
				var nome = $(this).data("nome");
				var tel = $(this).data("tel");
				$("#formPost").prepend("<input type='hidden' 
				name='" + listName + "[" + qtd + "].Nome' 
				value='"+nome+"'>");
				$("#formPost").prepend("<input type='hidden' 
				name='" + listName + "[" + qtd + "].Telefone' 
				value='" + tel + "'>");
				qtd += 1;
			});
		});
	});
</script>
}

The line below is important. Use the <code> attribute </code> date to inform the data that will be sent to the server:

C#
$("#tablePost > tbody").append("<tr data-nome='" + nome +
"' data-tel='"+ tel +"'><td>" +
nome + "</td><td>" + tel + "</td></tr>");

By clicking the "Post", get the data for each row added and create a hidden field with the name attribute in the form:

C#
    <input type='hidden' 
name='ModelListname[<ZERO to LASTROW>].Property' 
value='<value>' />

This is done by the code snippet below:

C#
var listName = "NomeTels";

var qtd = 0;
$("#tablePost > tbody > tr").each(function () {
    var nome = $(this).data("nome");
    var tel = $(this).data("tel");
    $("#formPost").prepend("<input type='hidden'
    name='" + listName + "[" + qtd + "].Nome'
    value='"+nome+"'>");
    $("#formPost").prepend("<input type='hidden'
    name='" + listName + "[" + qtd + "].Telefone'
    value='" + tel + "'>");
    qtd += 1;
});

This was the way I liked to post a list to the server without using JSON or other type of conversion. We use the data as common fields of forms.

Points of Interest

Everything has more than one way to be done (even if they say I didn't). This is one of the simplest ways to post data to your controller. Perhaps then, it is possible to create a jquery plugin? ;-)

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer
Brazil Brazil
Senior Developer C# and ASP.NET since 2002.

Comments and Discussions

 
QuestionHi - How to POST to Controller Pin
Member 155914355-Apr-22 5:03
Member 155914355-Apr-22 5:03 
PraiseThank you so much Pin
F@adi27-Jun-18 6:26
F@adi27-Jun-18 6:26 
QuestionHow to get the data posted Pin
Member 1278853711-Oct-16 19:53
Member 1278853711-Oct-16 19:53 
Questiongold cliff Pin
Member 1177406317-Jun-15 16:44
Member 1177406317-Jun-15 16:44 
Questionopinion Pin
Member 1177406317-Jun-15 16:39
Member 1177406317-Jun-15 16:39 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.