You can easily generate a dynamic view based on table from this simple lines of code
Controller
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
public class HomeController : Controller { public List<String> GetAllColumns(String tableName) { string connectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString; var columns = new List<string>(); using (var connection = new SqlConnection(connectionString)) { connection.Open(); String query = String.Format("select * from {0}",tableName); SqlCommand command = new SqlCommand(query, connection); var reader = command.ExecuteReader(); for (int i = 0; i < reader.FieldCount; i++) { columns.Add(reader.GetName(i)); } } return columns; } public class KeyValue { public String Column { get; set; } public String Value { get; set; } } public ActionResult Index() { List<String> columns = GetAllColumns("users"); return View(columns); } [HttpPost] public ActionResult Index(FormCollection fomr) { List<String> columns = GetAllColumns("users"); List<KeyValue> keyValues=new List<KeyValue>(); foreach (var col in columns) { KeyValue value = new KeyValue { Column = col, Value = Request.Form[col] }; keyValues.Add(value); } return View(); } } |
View
1 2 3 4 5 6 7 8 9 10 11 12 13 |
@model List<String> @using(Html.BeginForm("Index","Home",FormMethod.Post)) { for (int i = 0; i < Model.Count; i++) { @Model[i] <input type="text" name="@Model[i]" /> <br /> } <input type="submit" name="Submit" value="Submit" /> } |
Web.config
1 2 3 4 5 |
<connectionStrings> <add name="ConnectionString" connectionString="Data Source=(local);Integrated Security=false;Initial Catalog=test;User ID=sa;Password=abc" providerName="System.Data.SqlClient"/> </connectionStrings> |