asp.net-mvc,asp.net-mvc-4 , Dynamically adding controls in MVC4


Dynamically adding controls in MVC4

Question:

Tag: asp.net-mvc,asp.net-mvc-4

I am currently working on creating an MVC4 application where I want controls to be generated automatically from the database rows.

I have the table in my database containing the questions and the control type in which it should be answered by the user.

I am just thinking of a logic like

  1. Where I can get the database rows in a dataset and then foreach it, then checking the type of control it belongs and then creating the control in my View.

This is my Controller action:

Public ActionResult Index()
{
    // get the rows from the table 
    foreach(Iterate the rows)
    {
        if(controllerType1)
        {
            //stmnts
        }

        if(controllerType2)
        {
            //stmnts
        }       
    }
    return View();
}

This is just an idea of how can we build the solution. If I am going in the right way please guide me, else I am eager to know the possibilities where I can build my solution in different ways :).


Answer:

You can create a editor template and pass the control list as model to the template and in the template you can iterate that list to generate the control. As i have shown below.

1->Create a class for Control Information.

public class ControlInfo
    {
        public string ControlType { get; set; }
        public string ControlID { get; set; }
        public string ControlName { get; set; }
        public string ControlValue { get; set; }
        public string ControlLabel { get; set; }
        public bool IsChecked { get; set; }
    }

2->Create an Editor Template (Partial view with control name say CustomControl.cshtml) in \Views\Shared\EditorTemplates path.

   @model List<MvcApplication2.Models.ControlInfo>
    <table>

        @foreach (MvcApplication2.Models.ControlInfo ControlInfo in Model)
        {
            <tr>
                <td>@ControlInfo.ControlLabel</td>
                <td>
                @switch (ControlInfo.ControlType.ToLower())
                {
                    case "textbox":

                        <input type="text" name="@ControlInfo.ControlName" id="@ControlInfo.ControlID" value="@ControlInfo.ControlValue" />
                        break;
                    case "checkbox":
                        if (ControlInfo.IsChecked)
                        {
                            <input type="checkbox" name="@ControlInfo.ControlName" id="@ControlInfo.ControlID" value="@ControlInfo.ControlValue" checked="checked" />
                        }
                        else
                        {
                            <input type="checkbox" name="@ControlInfo.ControlName" id="@ControlInfo.ControlID" value="@ControlInfo.ControlValue" checked="checked" />
                        }

                        break;
                    default:
                        break;
                }
                </td>

            </tr>
        }

    </table>

3->Create a model for main view (say HomeModel).

 public class HomeModel
    {
        public List<ControlInfo> ControlList { get; set; }

        public void PolulateControlList()
        {
            //You can fill this list from database. 
            // For example i have filled the list manually.
            ControlList = new List<ControlInfo>();
            ControlList.Add(new ControlInfo() {ControlType="TextBox",ControlName="tbox1", ControlID="tbox1", ControlLabel="Name",  ControlValue="Martin"   });

            ControlList.Add(new ControlInfo() { ControlType = "CheckBox", ControlName = "cbox1", ControlID = "cbox1", ControlLabel="Is Correct", ControlValue = "Yes", IsChecked=true });
        }
    }

4->Consume the editor template in the main view as.

 @model  MvcApplication2.Models.HomeModel    
    @{
        ViewBag.Title = "Home Page";
    }

    @Html.EditorFor(model=>model.ControlList,"CustomControl")

5-> Call the main view in the controller ( Index here).

public ActionResult Index()
        {
            HomeModel ModelObj = new HomeModel();
            ModelObj.PolulateControlList();
            return View(ModelObj);
        }

Edit 1: For getting the posted value you need to modify the Editor Templates as below. The model properties whose name is equal to the name of the control posted as name value collection , will get automatically binded by the model binder of the mvc frame work, so for each property in the control collection i have created hidden tags and one input tag for the input value.

@model List<MvcApplication2.Models.ControlInfo>
<table>
    @{ var index = -1;}
    @foreach (MvcApplication2.Models.ControlInfo ControlInfo in Model)
    {
        index++;
        <tr>
            <td>@ControlInfo.ControlLabel</td>
            <td>
                <input type="hidden" name="@("ControlList[" + index + "].ControlID")" value="@ControlInfo.ControlID" />
                <input type="hidden" name="@("ControlList[" + index + "].ControlLabel")" value="@ControlInfo.ControlLabel" />
                <input type="hidden" name="@("ControlList[" + index + "].ControlName")" value="@ControlInfo.ControlName" />
                <input type="hidden" name="@("ControlList[" + index + "].ControlType")" value="@ControlInfo.ControlType" />

                @switch (ControlInfo.ControlType.ToLower())
                {
                    case "textbox":

                        <input type="text" name="@("ControlList["+index+"].ControlValue")" id="@ControlInfo.ControlID" value="@ControlInfo.ControlValue" />
                        break;
                    case "checkbox":
                         <input type="hidden" name="@("ControlList[" + index + "].ControlValue")" value="@ControlInfo.ControlValue" />
                        if (ControlInfo.IsChecked)
                        {
                            <input type="checkbox" name="@("ControlList[" + index + "].IsChecked")" id="@ControlInfo.ControlID" value="true" checked="checked" />
                        }
                        else
                        {
                            <input type="checkbox" name="@("ControlList[" + index + "].IsChecked")" id="@ControlInfo.ControlID" value="true" />
                        }

                        break;
                    default:
                        break;
                }
            </td>

        </tr>
    }

</table>

And in the main view you need to have form

@model  MvcApplication2.Models.HomeModel

@{
    ViewBag.Title = "Home Page";
}

@using(Html.BeginForm()){

@Html.EditorFor(model=>model.ControlList,"CustomControl")

 <input type="submit" name="name" value="Submit" />
}

And in controller you need to have corresponding post method

 [HttpPost]
        public ActionResult Index(HomeModel ModelObj)
        {
          // Your logic..........
            return View(ModelObj);
        }

This ModelObj will have the posted values.


Related:


How to use ajax to post json string to controller method?


jquery,asp.net-mvc,visual-studio-2013,asp.net-mvc-5
I want to be able to post a json string to a control action but it's always receive the string as null. If I create a view model for the controller method, it works, but that's not what I want since there will be too much view models to maintain....

Adding where clause to IEnumerable Select


c#,asp.net-mvc,linq
I have the following line of code in my controller that selects the id's of the interests shown within a view (they are listed down the page). IEnumerable<int> interestIds = viewModel.ExistingInterests.Select(x => x.InterestId); However I want to be able to add a where clause to the select section. In ExisitingInterests...

Url.Action Compilation Error : BC30988: Type or 'With' expected


javascript,c#,html,asp.net-mvc
I have code below, I need redirect to an other view page. function patrListClick(PAT_ID) { window.location.href = '<%: Url.Action("PatrList", "Patr", new { id = "_id_" }) %>'.replace('_id_', PAT_ID); } Unfortunately, I got compilation error. ...

Can I check if action is a child action in a view?


c#,asp.net-mvc,razor
I know that I can check if an action is a child action inside a controller, store the result in ViewBag or elsewhere and pass this information to the view, but assuming I don't want\can't modify the controller, is there some way to check if the current action is a...

HTTP Error 403.14


asp.net-mvc,visual-studio-2013
I'm developing my MVC 5 app using VS 2013, it was working fine, but suddenly it's giving the following error. HTTP Error 403.14 - Forbidden The Web server is configured to not list the contents of this directory. I've already read this post, and it didn't solve the problem. I've...

Strange situation, Visual Studio debugging ran through action to view but nothing returned to browser


c#,jquery,ajax,asp.net-mvc,razor
I have encountered a very strange problem. Basically, there is a Delete ActionLink. Once clicked, the code checks the condition, checks true/false, stays on current page or goes to Delete view. I have posted the solution for this scenario and got some very helpful replies. I worked on it and...

File IO Close() method error in ASP.NET MVC 6


asp.net-mvc,asp.net-mvc-6
I am doing a simple file IO in MVC6. I have added System.IO NuGet package. However, it gives me compile time error. VS IDE doesn't show any red mark when I type the code. The Close() method also appears in intellisense. Please help! My Code StreamWriter writer = System.IO.File.CreateText("some_valid_path"); writer.WriteLine("test");...

Unable to find the auto created Database


c#,asp.net,asp.net-mvc,entity-framework
I have created simple ASP.NET MVC4 application using EntityFramework Code first approach. The entity class is as below: public class Album { [Key] public int AblumId { get; set; } public decimal Price { get; set; } public string Title { get; set; } } public class MusicContext : DbContext...

Knockout JS Validation not working


javascript,asp.net-mvc,knockout.js
I am a newbie in Knockout JS. i want to apply validations in KO. i have used plugin knockout.validation.min.js . I have implemented it like this but not working My View Model $(document).ready(function myfunction() { ko.applyBindings(new EmployeeKoViewModel()); }) var EmployeeKoViewModel = function () { var self = this; self.EmpId =...

Dynamically adding controls in MVC4


asp.net-mvc,asp.net-mvc-4
I am currently working on creating an MVC4 application where I want controls to be generated automatically from the database rows. I have the table in my database containing the questions and the control type in which it should be answered by the user. I am just thinking of a...

When adding a user to a role in asp.net mvc 4.5, i'm getting an error- “user (user name) not found”


c#,asp.net-mvc
Here is my account login controller. (My "auth" class method returns "user" or "admin" and is logged in accordingly). [HttpPost] public ActionResult Login(string userName, string pass) { Auth auth = new Auth(); if (auth.MyAuth(userName) == "user") { FormsAuthentication.SetAuthCookie(userName, true); return RedirectToAction("Index", "Home"); } else if(auth.MyAuth(userName) == "admin") { FormsAuthentication.SetAuthCookie(userName, true);...

Conflicted with the REFERENCE constraint. How to solve this?


asp.net-mvc-4,nhibernate
I catch this GenericADOException exception but some unexpected exception comes again when I do genRep.Update(userW). How can I fix this problem? This is my code: public ActionResult DeleteUser(long? UserID) { GenericRepositoryV2 genRep ; if (!SecurityService.IsLoggedIn(Session)) { return SecurityService.LoginAndRedirect(Request); } try { genRep = new GenericRepositoryV2(); genRep.StartTransaction(); User user = genRep.GetById<User>(UserID);...

MVC 5 OWIN login with claims and AntiforgeryToken. Do I miss a ClaimsIdentity provider?


asp.net-mvc,asp.net-mvc-4,razor,asp.net-mvc-5,claims-based-identity
I'm trying to learn Claims for MVC 5 OWIN login. I try'ed to keep it as simple as possible. I started with the MVC template and inserted my claims code (see below). I get an error when I use the @Html.AntiForgeryToken() helper in the View. Error: A claim of type...

How to add validators for @Html.TextBox() without model


asp.net-mvc,asp.net-mvc-4
This is a part of my view @model bhavin.Models.Employee @using (Html.BeginForm("BuynowForm", "Home")) { <div class="form-group"> <label>Billing Address</label> @Html.TextBox("bill_address", null, new { @class = "form-control valid" }) </div> <p> <input type="submit" value="Submit" class="btn btn-primary" /> </p> } I want to add required validation to it. The billing_address textbox is not a...

Best approach to upgrade MVC3 web app to MVC5?


c#,.net,asp.net-mvc,asp.net-mvc-5
I have a web application which runs on Azure which is currently running MVC3/C#, EF6.1, .NET4.5. I would like to upgrade it to MVC5 to be: a) Current b) Get benefit of new features c) Get Performance gains. This is a part of a performance project, so hopefully there will...

which approach is best for GET,POST using Rest API [closed]


c#,jquery,asp.net-mvc,angularjs
i am using rest api to fetch and save the data in database using jquery or angularjs, but i want to ask you about which approach is best for doing this. using jquery to post the data using angularjs to post the data using c# code behind to post the...

How to hide columns in Kendo Grid when editing in a popup


asp.net-mvc,kendo-ui,kendo-grid,kendo-asp.net-mvc
I use Telerik Kendo Grid editing-inline. I want to hide certain columns when editing popup the number of columns....

How to use Autofac to inject specific implementation in constructor


c#,asp.net-mvc,dependency-injection,autofac
I have two classes that take a ILastActivityUpdator as a constructor parameter: UserService and AnonymousUserService. public AnonymousUserService(ILastActivityUpdator lastActivityUpdator) { if (lastActivityUpdator == null) { throw new ArgumentNullException("lastActivityUpdator"); } this.lastActivityUpdator = lastActivityUpdator; } And similar as above for UserService: public UserService(ILastActivityUpdator lastActivityUpdator) { if (lastActivityUpdator == null) { throw new ArgumentNullException("lastActivityUpdator");...

devenv.exe hogs CPU when debugging


asp.net-mvc,visual-studio-2013
Short version: When I debug ASP.NET MVC apps in VS2013 and try to edit razor views or css files, the CPU usage of devenv.exe skyrockets to the point where VS becomes unresponsive. Browser link is turned off, yet this still happens. Restarting debugging doesn't help, restarting VS doesn't help, restarting...

Avoid EF update the null image to database in .Net MVC


asp.net-mvc,entity-framework,null,edit,httppostedfilebase
In my SachController, there is an Edit method like below. In the view, there are several textbox and one file-input for upload image object. Sometime, user doesn't want to change the image and they just don't select a new image. And the image (HttpPostedFileBase) is null. How can I avoid...

Creating a viewmodel on an existing project


c#,asp.net,asp.net-mvc
I am trying to add a viewmodel to a project because I want my view to use two separate models. I've looked at different tutorials trying to learn how to do this but I am having some trouble. Before, the view was strongly binded(typed?) to the Person model, but now...

.NET MVC: Finding default Bootsrap JavaScripts


javascript,asp.net-mvc,twitter-bootstrap
In an out-of-the-box implementation of an MVC app using Bootstrap in Visual Studio 2013, there seems to be some javasvript that works on this element: <li role="presentation" class="dropdown"> .... </li> When that element is clicked, there is, somewhere, some JavaScript that changes the class in this element to: <li role="presentation"...

check if file is image


c#,asp.net,asp.net-mvc
I want to check if file is image. and then you will see a link where you can see the image. But the link only has to appear if file is link. I try it like this: if (!String.IsNullOrEmpty(item.FileName)) { var file = item.FileName; string[] formats = new string[] {...

MVC Push notification from server to client side


asp.net-mvc-4,push-notification
This question may sound lame but. Is there any technique to send push notificaiton from server to client side, regarding the server status. For Example: While Login Notification in Client Side in sequence: Validating User ... Validating Digital Certificate ... Sorting downloadable file ... Preparing to download ... If its...

C# Using Bool, how to check a double is truly divisible by another number? [duplicate]


c#,asp.net-mvc-4
This question already has an answer here: How can I calculate divide and modulo for integers 4 answers Is there a way of checking that a value is wholly divisible by another number, for example 1000 divided by 100 would be true, but 1115 divided by 100 would be...

ASP.NET httpHandlers & handlers


asp.net,asp.net-mvc
I am confused about httpHandlers in system.web and handlers in system.webServer. What is the difference between these two configuration? And how and when to use them? Actually another question is for modules as well: httpModules in system.web and modules in system.webServer...

C# entity framework MVC second run error


entity-framework,asp.net-mvc-4,localdb
I am creating db and initializing data with code below, if DB doesnt exist, it creates db and populate it, when I run application second time I get error Cannot drop database "aspnet-app" because it is currently in use. Application_start, with initializations protected void Application_Start() { AreaRegistration.RegisterAllAreas(); WebApiConfig.Register(GlobalConfiguration.Configuration); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes);...

How to Convert a Time to local Time in Different TimeZone


c#,asp.net,asp.net-mvc,timezone,timezoneoffset
Currently i am working on a chat project from where many users can communicate through each other sitting across the globe. ie: Different TimeZone. eg. 1st in India 2nd in America 3rd in Russia 4th in Australia I am saving my message sent time into database as DateTime.Now.ToUniversalTime() Issue i...

How to get started with Visual studio 2012


c#,asp.net-mvc,asp.net-mvc-3,asp.net-mvc-4,visual-studio-2012
I want to create web application using Visual Studio 2012. The application should login into a website and report numerical findings on the UI. The language used will be Visual C#. I have loaded the application and selected on the menu: File> New > Projects. A window appears with multiple...

How to Implement Dependent Dropdownlist in MVC4 Razor and using SQL server also


sql-server,asp.net-mvc-4,razor
I've 2 Dropdownlist called States and Country. but only the States DDL(DropdownList) will be enable the country DDL will be diable. when I select a option in States which is already stored in SQL. The Country DDL Should Show the Selected state's Country automatically from DB. Please help Me..... Ex:If...

Angularjs resource with scope parameter


javascript,asp.net-mvc,angularjs,single-page-application
My problem is the following: I am trying to call resource with the following parameter and I get the following error: [$resource:badcfg] I tried fixing this in the past 3 hours and I cant seem to make it work. So, if i call it like this: $scope.komintent = Fakturi.komintenti.get({ id:...

How to map between two entities before paging


c#,asp.net-mvc,entity-framework
Consider the code below: public ActionResult Index(int? page) { List<ProviderViewModel> viewModel = new List<ProviderViewModel>(); List<Provider> businessModel = db.Providers .OrderBy(t => t.Name); foreach (Provider provider in businessModel) { viewModel.Add(new ProviderViewModel(provider)); } int pageSize = 9; int pageNumber = (page ?? 1); return View(viewModel.ToPagedList(pageNumber, pageSize)); } I'm using PagedList.MVC (from NuGet) and...

ASP.NET MVC Client side time convert from model


javascript,asp.net-mvc,model
My cshtml page contains the following code for DateTime, which is some server time fetched from sql. <tbody> @{ foreach (var item in Model) { <tr> <td> @Html.DisplayFor(modelItem => item.someDate) </td> The type of the someDate property is DateTime. I would like to show the time in respect to client/browser...

How to format label in ASP.net chart control


c#,asp.net,asp.net-mvc,c#-4.0,reporting-services
I have created a column chart in asp.net. I am showing the date on x-axis. At the moment the date is shown as dd/mm/yyyy. All I need is to show the date as dd-mm-yy and ideally Weekday, dd-mm-yy e.g. Monday, 12-05-15. <asp:Chart ID="Chart1" runat="server" Height="400px" Width="900px" BorderWidth = "1"> <Series>...

Why is my View not displaying value of ViewBag?


c#,asp.net,asp.net-mvc,asp.net-mvc-4,razor
I have a little blog application with posts and tags. This is my model for Post: namespace HelloWorld.Models { public class Post { [Required] [DataType(DataType.Text)] public string Title { get; set; } [Required] [DataType(DataType.MultilineText)] public string Description { get; set; } [Required] [DataType(DataType.DateTime)] public DateTime PostDate { get; set; }...

Output Raw String in ASP.NET MVC Razor [duplicate]


c#,asp.net-mvc,razor
This question already has an answer here: Emitting unencoded strings in a Razor view 4 answers I have a site built with ASP.NET MVC. I have a string in my view model that looks like this: ViewBag.Text = "{\"1\":{\"1\":\"John\",\"2\":\"Bill\",\"3\":\"Paul\"},\"3\":{}}"; I want to output this into my view like this:...

MVC route attribute no controller


asp.net-mvc,asp.net-mvc-5,asp.net-mvc-routing
I'm building an intranet where I have the following home controller: [Route("{action=index}")] public class HomeController : Controller { public ActionResult Index() { return View(HomeModelBuilder.BuildHomeModel()); } public ActionResult FormsHome() { return View(HomeModelBuilder.BuildFormsHomeModel()); } } I'm trying to get my forms homepage to have a url of http://intranet/forms so I thought I...

How to enable multiple login tries in asp.net forms authentication?


c#,asp.net,asp.net-mvc,authentication
I have a MVC project with forms authentication. Basically it works fine: The user wants to access a controller with Authorize-Attribute and gets redirected to login-page if not authenticated. On redirect the parameter returnUrl gets forwarded as well. However, in case the first try of the login fails, the return...

Multiple Posted Types asp.net 5 MVC 6 API


c#,asp.net,asp.net-mvc,asp.net-5,asp.net-mvc-6
I can use [FromBody] for single type , but is there any way to use multiple? From the searching and reading I've done there is not a way, but i don't know if a way has been added in MVC 6. If not, where would be best to start with...

Checkbox to be checked on having value Y


asp.net-mvc,knockout.js
I have a checkbox bound to a viewmodel's observable property, whose value will be Y or N. I want the the checkbox to be checked when the value is Y and unchecked when the value is N. How to achieve this? I am able to achieve it if the value...

System.net.http.formatting causing issues with Newtonsoft.json


c#,asp.net,asp.net-mvc,json.net
My Windows service is in the same solution as a MVC project. The MVC project uses a reference to SignalR Client which requires Newtonsoft.Json v6 + the Windows service uses System.Net.Http.Formatting, which requires Newtonsoft.Json version 4.5.0.0. I assumed this would not be a problem, as I could just use a...

Show/hide tinymce with radio buttons


c#,asp.net,asp.net-mvc,tinymce
I try to show/hide a tinymce with radobutton. Like yes/no. So there are two radio buttons. yes - will show the tiny mce and no will hide the tinymce. I have this: showing tiny mce: <div class="form-group"> @Html.Label(Resources.Entity.Product.PdfMessage, new { @class = "text-bold control-label col-md-2" }) <div class="col-lg-6 col-md-8 col-sm-10...

ASP.NET MVC posting list from view to controller


c#,.net,asp.net-mvc,razor
I have a view model in my ASP.NET MVC application: public class FiltersViewModel { public IEnumerable<SelectListItem> AvailableFilters { get; set; } // fills a drop down menu public IList<TechnologyFilter> TechnologyFilters { get; set; } public IList<ContractTypeFilter> ContractTypeFilters { get; set; } public FiltersViewModel() { this.TechnologyFilters = new List<TechnologyFilter>(); this.ContractTypeFilters =...

Database object with different data


sql,asp.net,asp.net-mvc,database,entity-framework-6
I'm making a web page in ASP.NET MVC which compares prices from different shops. I have a one-to-many with products and the shops, where the SHOP has one PRODUCT and a PRODUCT has many SHOPs, the problem is that the product is the same but the price is different. Example:...

How to get Display Text from EnumDropDownListFor on post?


c#,asp.net-mvc,enums,html-helper
Is there a way to get DisplayName (Text) from EnumDropDownListFor helper for enum? Enum: public enum PartnersGroup { [Display(Name="Partner_SystemsGroup",ResourceType=typeof(Global) )] SystemsGroup, [Display(Name="Partner_SoftwarePartners",ResourceType=typeof(Global))] SoftwarePartners, [Display(Name="Partner_IntegrationPartners",ResourceType=typeof(Global))] IntegrationPartners, } Model public class Partner { public PartnersGroup PartnersGroup { get; set; } } Controller // GET: Partners/Create public ActionResult Create() { ---- return...