0

I use this code to generate dynamic controls in MVC.

I am working on MVC Application. The Control names are stored in database like there is 5 rows that contains control name (ex. texbox, dropdown) and I retrieve that data from database on button click using pure MVC.

Now how to retrieve that controls' value in controller.

In model:

public class Controls {
    public string ControlName{get;set;}
}

In controller:

public ActionResult Index()
{
    List<Controls> _controls=new List<Controls>();//retrieve 
    data from db in your case

    var _c=new Controls();
    _controls.Add(new Controls(){ControlName="textbox"});
    _controls.Add(new Controls(){ControlName="radio"});
    return View(_controls); // 
}

In view:

@model List<Controls>
@foreach(var item in Model) {
    <input type="@item.ControlName">
}
NightOwl888
  • 55,572
  • 24
  • 139
  • 212
V-Vek P-Tel
  • 77
  • 1
  • 10
  • Your input does not have a `name` attribute so wont post back anything –  Feb 07 '18 at 09:02
  • but how to retrive that value in controller because controls are not binded with modal – V-Vek P-Tel Feb 07 '18 at 09:07
  • Your model needs a property for the name of the control (you existing property is for the type of the control) Then you need to add a `name="@item.Name"`, but that will not bind to a collection anyway - refer [Post an HTML Table to ADO.NET DataTable](http://stackoverflow.com/questions/30094047/html-table-to-ado-net-datatable/30094943#30094943) to understand how to generate form controls for a collection (but there are so many other problems with your code and implementation that its impossible to know where to start) –  Feb 07 '18 at 09:21
  • I already add the name property to my unique code that is saved to the database against that control so how can i proceed for same – V-Vek P-Tel Feb 07 '18 at 09:28

0 Answers0