C# dynamic report fields

**Controller** public class HomeController : Controller { public ActionResult Index() { return View(); } public ActionResult Report(string id) { Report model = Database.GetReport(id); return View(model); } [HttpPost] public ActionResult Report(Report model) { foreach (ReportSection section in model.Sections) { Debug.Print(section.Content); } return View(model); } } **Report View** @using MyApplication.Models @model Report @using (Html.BeginForm()) { <div class="form-horizontal"> <h4>Report</h4> <hr /> @Html.ValidationSummary(true) <div class="form-group"> @Html.LabelFor(model => model.Title, new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.EditorFor(model => model.Title) @Html.ValidationMessageFor(model => model.Title) </div> </div> <div class="form-group"> @Html.LabelFor(model => model.Description, new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.EditorFor(model => model.Description) @Html.ValidationMessageFor(model => model.Description) </div> </div> <table> @for (int i = 0; i < Model.Sections.Count; i++) { ReportSection section = Model.Sections[i]; <tr> <td>@Html.Label(section.Title)</td> <td>@Html.TextBox("Sections[" + i + "].Content", section.Content)</td> @Html.Hidden("Sections[" + i + "].Title", section.Title) </tr> } </table> <input type="submit" value="Create" class="btn btn-default" /> </div> } **Test data** Returning some dummy data for testing. public class Database { public static Report GetReport(string id) { return new Report() { Title = "Report" + id, Description = "my test report " + id, Sections = new List<ReportSection> { new ReportSection { Title = "Section 1", Content = "content for section 1" }, new ReportSection { Title = "Section 2", Content = "content for section 2" } } }; } }

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.