Retrieve the value of a dynamically generated field

1

Good morning. I would like to know how do I retrieve the value of the control that is generated dynamically in my form at runtime? Type below in the image I have a class that brings all the properties of the controls to be shown in the Client View. In it I bring the type of HTML control, the CSS class that will be used, the order that this control will appear on the page, etc, everything already preconfigured in the database:

AtthetimeIsubmitandthemodelisnotvalid,Icannotretrievethevaluetypedinthefieldasshownonthepagebelow:

I'mtryingtomakethistypeofgenerationofdynamiccontrolswork,thinkingofasign-upsystemwhereyoucanhavemultipleclientswithdifferentsignscreens,differentfields,differentdisplaynames,theordereachlabelorinputappears,etc.Thinkingaboutthisscenariomakesiteasytoassembleallscreensaccordingtotherequirementsofscreenswithsay10clientswithdifferentscreens,withouthavingtotinkerwithmyViews.Itriedtodothis,butifsomeoneisabetterideathatcanhelpmetogeneratethesecontrolsdynamicallywithouthavingtocreatemultipleviewsintheproject,thankyouorhelpmefollowingthislogicthatIdid.

usingSystem;usingSystem.Collections.Generic;usingSystem.ComponentModel;usingSystem.ComponentModel.DataAnnotations;namespaceProjetoModeloDDD.MVC.ViewModels{publicclassClienteViewModel{[Key]publicintClienteId{get;set;}[Required(ErrorMessage="Preencha o campo Nome")]
        [MaxLength(150, ErrorMessage = "Máximo {0} caracteres")]
        [MinLength(2, ErrorMessage = "Minimo {0} caracteres")]
        public string Nome { get; set; }

        [Required(ErrorMessage = "Preencha o campo Sobrenome")]
        [MaxLength(150, ErrorMessage = "Máximo {0} caracteres")]
        [MinLength(2, ErrorMessage = "Mínimo {0} caracteres")]
        public string Sobrenome { get; set; }

        [Required(ErrorMessage = "Preencha o campo Endereço")]
        [MaxLength(150, ErrorMessage = "Máximo {0} caracteres")]
        [MinLength(2, ErrorMessage = "Mínimo {0} caracteres")]
        [Display(Name = "Endereço")]
        public string Endereco { get; set; }

        [Display(Name = "Ponto de Ref.")]
        public string PontoReferencia { get; set; }
        public string Telefone { get; set; }

        [Display(Name = "Data de Nascimento")]
        public DateTime DataNascimento { get; set; }

        [Required(ErrorMessage = "Preencha o campo E-mail")]
        [MaxLength(100, ErrorMessage = "Máximo {0} caracteres")]
        [EmailAddress(ErrorMessage = "Preencha um E-mail válido")]
        [DisplayName("E-mail")]
        public string Email { get; set; }

        [ScaffoldColumn(false)]
        public DateTime DataCadastro { get; set; }

        public bool Ativo { get; set; }
        public virtual IEnumerable<ProdutoViewModel> Produtos { get; set; }

        public IEnumerable<MenuConfigViewModel> MenuConfigViewModels { get; set; }
    }
}

View Create Client Code

@using ProjetoModeloDDD.MVC.Helpers
@model  ProjetoModeloDDD.MVC.ViewModels.ClienteViewModel


@{
    ViewBag.Title = "Create";


}

<h2>Create</h2>


@using (Html.BeginForm()) 
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>ClienteViewModel</h4>
        <hr />fma

        @if (Model.MenuConfigViewModels != null)
        {
            foreach (var item in Model.MenuConfigViewModels)
            {
                if (item.TagHtml.Equals("input"))
                {
                    @Html.ValidationSummary(true, "", new { @class = "text-danger" })
                    <div class="form-group">
                        @HtmlHelpers.MyInputHelper(item.Name, item.Name, "", htmlAttributes: new { @class = "form-control text-box single-line input-validation-error" })
                        @*@Html.ValidationMessageFor(model => model.Nome, "", new { @class = "text-danger" })*@
                    </div>
                }

            }

        } 

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </div>
    </div>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}
    
asked by anonymous 31.10.2016 / 14:30

1 answer

1

What you want is one (or all) of the principles by which SOLID

p>

Create an interface, enter all the fields that will necessarily exist for all 10, 100, N clients

public interface IClienteDaAplicacaoModel
{
    Int32 ClienteId {get;set;}
    String CPF {get;set;}
    String Email {get;set;}
}

Now for each client, create a concrete template that inherits the interface

public sealed class ClienteXModel : IClienteDaAplicacaoModel
{
    public String CampoEspecificoDoClienteX {get;set;}
    public String CNPJ {get;set;}
}

public sealed class ClienteYModel : IClienteDaAplicacaoModel
{
    public Int64 TelefoneContato {get;set;}
}

public sealed class...outros clientes

From here on, you work with the Interface, not with its implementations, and use Reflection to get the fields of each implementation according to the use

In addition to the links above, some more on SOLID and Reflection

* I used sealed in concrete examples, but they can be abstract or not sealed if you want them to be inherited by other clients (let's assume that client Z has everything from client X and interface, then in this case it would just inherit X on Z instead of having the same fields from X on Z again)

    
14.01.2017 / 20:44