Record Email and Phone Array in Database with Entity

Asked

Viewed 248 times

3

I need to save an html array of telefones and Emails, in the database, but I’m not sure how to receive such data. Phone and email number can be 0 ou N, as in the image below, one can add as many input as they want.

So I needed to be able to receive the data, so I could put it in the bank ("Essa parte eu sei"), I’m just not getting paid, because my model always arrives vazio, in the telephone fields:

inserir a descrição da imagem aqui This is my script that duplicates the input

CloneTelephone = function () {
    var cloneTel = $('#dynamicDivTel');

    $(document).on('click', '#addTel', function () {
        $('<span>' +
            '<label class="form-control-label" for="">Telefone ou Celular</label>' +
            '<div class="input-group form-group">' +
            '<input type="text" class="form-control phone" placeholder="Telefone ou Celular">' +
            '<div class="input-group-append">' +
            '<button class="btn btn-danger" type="button" id="delTel"><i class="fas fa-minus"></i></button>' +
            '</div>' +
            '</div>' +
            '</span>').appendTo(cloneTel);
        return false;
    });

    $(document).on('click', '#delTel', function () {
        $(this).parents('span').remove();
        return false;
    });

}(),

That’s the part of mine form:

<div class="pl-lg-4">
    <div class="row">
        <div class="col-lg-6" id="dynamicDivTel">
            <label class="form-control-label" asp-for="Phones">Telefone ou Celular</label>
            <div class="input-group form-group">
                <input type="text" class="form-control phone" asp-for="Phones" placeholder="Telefone ou Celular">
                <div class="input-group-append">
                    <button class="btn btn-primary" type="button" id="addTel"><i class="fas fa-plus"></i></button>
                </div>
            </div>
            <span asp-validation-for="Phones" class="text-danger"></span>
        </div>
        <div class="col-lg-6" id="dynamicDivEmail">
            <label class="form-control-label" asp-for="Emails">Email</label>
            <div class="input-group form-group">
                <input type="email" class="form-control" asp-for="Emails" placeholder="Email">
                <div class="input-group-append">
                    <button class="btn btn-primary" type="button" id="addEmail"><i class="fas fa-plus"></i></button>
                </div>
            </div>
            <span asp-validation-for="Emails" class="text-danger"></span>
        </div>
    </div>
</div>

And this is mine ViewModel:

public class AddCondominiumViewModel
{
    [Required(ErrorMessage = "Razão Social é um campo obrigatório")]
    [StringLength(100, ErrorMessage = "A {0} deve ter pelo menos {2} e no máximo {1} caracteres.", MinimumLength = 3)]
    [Display(Name = "Razão Social")]
    public String CompanyName { get; set; }

    [Required(ErrorMessage = "Nome Fantasia é um campo obrigatório")]
    [StringLength(100, ErrorMessage = "O {0} deve ter pelo menos {2} e no máximo {1} caracteres.", MinimumLength = 3)]
    [Display(Name = "Nome Fantasia")]
    public String FantasyName { get; set; }

    [Required(ErrorMessage = "CNPJ é um campo obrigatório")]
    [Display(Name = "CNPJ")]
    [RegularExpression(@"\d{2,3}.?\d{3}.?\d{3}/?\d{4}-?\d{2}", ErrorMessage = "CNPJ está em um formato inválido.")]
    public string Cnpj { get; set; }

    [Display(Name = "Data de Construação")]
    public Nullable<DateTime> ConstructionDate { get; set; }

    [Display(Name = "Tipo de Condomínio")]
    public string CondominiumType { get; set; }

    [RegularExpression(@"^\d{5}-\d{3}$", ErrorMessage = "CEP está em um formato inválido.")]
    [Display(Name = "CEP")]
    public string Cep { get; set; }

    [Display(Name = "Endereço")]
    public string Address { get; set; }

    [Display(Name = "Cidade")]
    public string City { get; set; }

    [Display(Name = "Bairro")]
    public string District { get; set; }

    [Display(Name = "UF")]
    public string Uf { get; set; }

    [Display(Name = "Número")]
    public Nullable<int> Number { get; set; }

    [Display(Name = "Complemento")]
    public string Complement { get; set; }

    [Display(Name = "Observação")]
    public string Note { get; set; }

    public IEnumerable<EmailViewModel> Emails { get; set; }

    public IEnumerable<PhoneViewModel> Phones { get; set; }

    public BankViewModel Banks { get; set; }
}

public class EmailViewModel
{
    [Display(Name = "Email")]
    [RegularExpression(@"^(([A-Za-z0-9]+_+)|([A-Za-z0-9]+\-+)|([A-Za-z0-9]+\.+)|([A-Za-z0-9]+\++))*[A-Za-z0-9]+@((\w+\-+)|(\w+\.))*\w{1,63}\.[a-zA-Z]{2,6}$", ErrorMessage = "Email está em um formato inválido.")]
    public string Email { get; set; }
}

public class PhoneViewModel
{
    [Display(Name = "Telefone ou Celular")]
    [RegularExpression(@"^\([1-9]{2}\) (?:[2-8]|9[1-9])[0-9]{3}\-[0-9]{4}$", ErrorMessage = "Telefone ou Celular estão em um formato inválido.")]
    public string Phone { get; set; }
}

public class BankViewModel
{
    [Display(Name = "Banco")]
    public string Bank { get; set; }

    [Display(Name = "Agência")]
    public Nullable<int> Agency { get; set; }

    [Display(Name = "Conta Corrente")]
    public Nullable<int> AccountCurrent { get; set; }
}

My Controller:

[HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Add(AddCondominiumViewModel model, string returnUrl = null)
    {
        ViewData["ReturnUrl"] = returnUrl;
        if (ModelState.IsValid)
        {

        }

        return View(model);
    }

They could help me in what I’m doing wrong, because I’m always receiving phone data as a Count = 0 ?

  • where the endpoint that receives the information from the form?

  • He carries a model behind the Viewmodel I put in question

  • Show your controller action

  • @Leandroangelo, I added mine controller in the question;

  • @Lucasmiranda ..

  • In fact the ideal would be a separate table with the information and a field fk that will connect the contact with the client, ie la the table that you will link

  • Yes, I am doing this. But I need to receive data from multiple phones in Viewmodel to be able to insert in the tables

  • The model is completely empty or just the phone list?

  • Just phone and email. They get Count = 0;

  • Check that your front end is sending Emails and Phones as arrays to convert to the list.

  • I’ve tried that way, but I still don’t get.

  • When that input <input type="text" class="form-control phone" asp-for="Phones" placeholder="Telefone ou Celular"> is redeveloped in the browser, as is the id or name his?

Show 8 more comments

1 answer

1


The problem is that you create fields dynamically and therefore the name="Fieldname" is not recognized by the controller.

Remember that when making an Asp-for="Model.Property" you are just making a shortcut to:

value="@Model.Propriedade"
name="Propriedade"

There are 3 ways to do it, I’ll explain 2:

1. Using the Begincollection component - Best option!

install the package:

Install-Package BeginCollectionItemCore -Version 1.0.8

https://www.nuget.org/packages/BeginCollectionItemCore/

(if it’s not Asp.net core look for the right package) Detailed help to do: http://blog.stevensanderson.com/2010/01/28/editing-a-variable-length-list-aspnet-mvc-2-style/

A fully functional demo you find in: https://github.com/saad749/BeginCollectionItemCore/tree/master/BeginCollectionItemCoreDemo Put a breackPoint on the controller and understand how it works.

2. Retrieving the names in the 'nail'

In javascript you will create a field dynamically, with the name of the type

name="Telefone_1"

public async Task<IActionResult> Add([FromBody] form)
{
var Tel1 = Request.Form["Telefone_1"];

}

And so for each field, you can send an Hidden field to know the Qtd. of fields. But again, I recommend using Begin Collection. If you have any questions with him open a new question.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.