I'm new to MVC. Now I'm trying with a simple demo of MVC that to print Customer's information to screen and update it, send back to database.
I have no idea why the Customer's ID becomes null while the others are fine.
I want to display Customer's ID to the screen but I don't want user to edit it to post to my database. I've been researching this for some hours now..
my code :
Customer.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace PeopleManagement.Models
{
public class Customer
{
[Required]
public string Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public Customer()
{
}
public Customer(string id, string name, int age)
{
Id = id;
this.Name = name;
this.Age = age;
}
}
}
Index.cshtml
@using System.Web.UI.WebControls
@using PeopleManagement.Models
@model IList<Customer>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>First MVC Application</title>
<link href="@Url.Content("~/Content/css/customized-table.css")" rel="stylesheet" type="text/css" />
</head>
<body style="max-width:100%; max-height:100%">
<div id="pageTitle" style="text-align:center; color:red; font-size:24px; font-weight:bold;">Customer Management</div>
@using (@Html.BeginForm("Index", "Home", FormMethod.Post))
{
<div id="tablePanel" style="padding-top: 15px">
<table class="customized_table" border="1">
<tr>
<th>ID</th>
<th>Name</th>
<th>Age</th>
</tr>
@{
for (var i = 0; i < Model.Count; i++)
{
<tr>
<td>
@Html.HiddenFor(model => model[i].Name);
</td>
<td>
@Html.TextBoxFor(model => model[i].Name, new {@style = "min-width:100%; text-align:center", @disable = "true"})
</td>
<td>
@Html.TextBoxFor(model => model[i].Age)
</td>
</tr>
}
}
</table>
</div>
<div>
<p><input type="submit"/></p>
</div>
}
</body>
</html>
<script>
</script>
HomeController.cs
using System.Collections.Generic;
using System.Web.Mvc;
using PeopleManagement.Models;
namespace PeopleManagement.Controllers
{
public class HomeController : Controller
{
public List<Customer> CustomersList { get; private set; } = new List<Customer>(5);
[HttpGet]
public ActionResult Index()
{
CustomersList.Add(new Customer("ID_1", "Name_1", 1));
CustomersList.Add(new Customer("ID_2", "Name_2", 2));
CustomersList.Add(new Customer("ID_3", "Name_3", 3));
ModelState.Clear();
return View(CustomersList);
}
[HttpPost]
public ActionResult Index(List<Customer> postbackCustomers)
{
if (!ModelState.IsValid)
return View(CustomersList);
CustomersList = postbackCustomers;
return View(CustomersList);
}
}
}
Can anyone help ?