Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

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

0.00/5 (No votes)
17 Jun 2015 1  
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:

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:

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.

@{
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:

    $("#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:

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

This is done by the code snippet below:

			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 has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here