locked
Is it possible to use a jquery input tags and insert into SQL Server? RRS feed

  • Question

  • User-733224187 posted

    Hello everyone, I would like to know if it is possible to insert data from a jquery input tags in SQL Server, I am doing a registration of groups of companies and to facilitate the user created a model for the Group where it takes the group id, name and a cnpjs list from another table.

    Model Group:

    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    using System.Linq;
    using System.Web;
    
    namespace mia.Models
    {
        public class Grupo
        {
            [Key]
            public int id { get; set; }
            public string nome_grupo { get; set; }
            public List<Cliente_TinyId_CNPJ> cnpjs { get; set; }
        }
    }

    Model Company:

    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    using System.Linq;
    using System.Web;
    
    namespace mia.Models
    {
        public class Cliente_TinyId_CNPJ
        {
            [Key]
            public int id { get; set; }
            public string cnpj { get; set; }
            public string id_tiny { get; set; }
            public string pagina_requisicao { get; set; }
        }
    }

    view Create:


    @model mia.Models.Grupo

    @{
    ViewBag.Title = "Novo Grupo";
    Layout = "~/Views/Shared/_Layout.cshtml";
    }

    @section Scripts {


    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"
    integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo"
    crossorigin="anonymous">
    </script>
    <link rel="stylesheet" href="~/Content/Fancymegatags/fancymetags.css">

    <script src="~/Scripts/Fancymegatags/fancymetags.jQuery.js"></script>

    <script>

    $('#btn-salvar').click(function () {
    var cnpjs = $('#shownlist').ready();

    alert(cnpjs);
    });
    $("#btn-adicionar").click(function () {
    alert("Handler for .click() called.");
    });
    </script>

    <script>
    //$(function () {
    // $("#tagfield").fancymetags({
    // theme: "blue",

    // });
    //});


    function getTags(){//Gets array of existing tags
    var alltags = new Array();
    var i = 0;
    $(".fancyme-tags #shownlist span").each(function( index ) {
    alltags[i] = $(this).html().substr(0,$(this).html().length - 20);
    i ++;
    });
    return alltags;
    };

    function setTags(){//Gets string of existing tags separated by commas
    var texttags = getTags();
    var finaltext = "";
    for(var i=0; i<texttags.length; i++){
    if(finaltext == ""){
    finaltext = texttags[i];
    }
    else{
    finaltext = finaltext + "," + texttags[i];
    }
    }
    return finaltext;
    }

    function addTags(){
    var tags = $(".fancyme-tags input[type=text]").val().trim();
    var listnews = "";
    var newtags = "";
    var existenttags = getTags();
    //checks if a comma was left alone at the end and removes it
    if(tags.substr(tags.length - 1) == ","){
    tags = tags.substr(0, tags.length -1);
    }
    //checks if a comma was left alone at the beginning and removes it
    if(tags.substr(0,1) == ","){
    tags = tags.substr(1, tags.length);
    }
    //if more than one tag was added
    if(tags.indexOf(",") !== -1){
    var artags = tags.split(',');
    for(var i=0; i<artags.length; i++){
    if((artags[i].trim() !== "")&&($.inArray(artags[i].trim(), existenttags) == -1)){
    listnews = listnews + '<span>'+artags[i].trim()+' | <a href="#">x</a></span>';
    existenttags.push(artags[i].trim());
    }
    }
    }
    //else if just one tag was added
    else{
    if($.inArray(tags, existenttags) == -1){
    listnews = '<span>'+tags+' | <a href="#">x</a></span>';
    }
    }
    //adds everything to the html and clears the value of the textfield
    $(".fancyme-tags #shownlist").append(listnews);
    $(".fancyme-tags input[type=text]").val("");
    $(".fancyme-tags #hiddenlist").html(setTags());
    };
    //event listeners for button and for the enter keypress
    $(".fancyme-tags input[type=button]").click(addTags);
    $(".fancyme-tags input[type=text]").keypress(function(e){
    if(e.which == 13){
    addTags();
    }
    });
    //erase event binding for the Xs in each tag
    $(document).on('click','.fancyme-tags #shownlist span a', function(){
    event.preventDefault();
    var btn = $(this);
    var hiddens = $(".fancyme-tags #hiddenlist").text();
    var tag = btn.parent().html().toString();
    tag = tag.substr(0,tag.length-20);
    btn.parent().remove();
    $(".fancyme-tags #hiddenlist").html(setTags());
    });
    </script>
    <script type="text/javascript">
    function cpfCnpj(v) {

    //Remove tudo o que não é dígito
    v = v.replace(/\D/g, "")

    if (v.length <= 11) { //CPF

    //Coloca um ponto entre o terceiro e o quarto dígitos
    v = v.replace(/(\d{3})(\d)/, "$1.$2")

    //Coloca um ponto entre o terceiro e o quarto dígitos
    //de novo (para o segundo bloco de números)
    v = v.replace(/(\d{3})(\d)/, "$1.$2")

    //Coloca um hífen entre o terceiro e o quarto dígitos
    v = v.replace(/(\d{3})(\d{1,2})$/, "$1-$2")

    } else { //CNPJ

    //Coloca ponto entre o segundo e o terceiro dígitos
    v = v.replace(/^(\d{2})(\d)/, "$1.$2")

    //Coloca ponto entre o quinto e o sexto dígitos
    v = v.replace(/^(\d{2})\.(\d{3})(\d)/, "$1.$2.$3")

    //Coloca uma barra entre o oitavo e o nono dígitos
    v = v.replace(/\.(\d{3})(\d)/, ".$1/$2")

    //Coloca um hífen depois do bloco de quatro dígitos
    v = v.replace(/(\d{4})(\d)/, "$1-$2")

    }

    return v

    }
    </script>
    }

    @using (Html.BeginForm())
    {
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    <div class="form-horizontal">
    <h4> Novo Grupo Empresarial </h4>
    <hr />
    <div class="container">
    <div class="row" style="margin-bottom:10px;">
    <label class="control-label col-md-2">Nome do Grupo</label>

    <div class="col-11" style="padding-right:0px; padding-bottom:5px">

    <input type="text" id="Nome_Grupo" class="form-control" required data-val="true" name="Nome_Grupo" value="@ViewBag.Nome_Grupo">

    </div>

    </div>

    <div class="form-group">
    <label>CNPJ</label>
    <div class="row blue fancyme-tags" id="tagfield">
    <div class='col-10' style='padding-right: 0px;'><input type='text' /><div id='shownlist'></div><div id='hiddenlist'></div></div>
    <div class='col-2' style='padding-left:0'><input class='btn btn-outline-primary btn-md' type='button' value='Adicionar' id='btn-adicionar' /></div>
    </div>
    </div>

    <div class="row fancyme-tags">
    <div class="col">
    <button type="submit" class="btn btn-outline-success" id="btn-salvar" onclick="RemoveMaskAndSubmit()">Salvar</button>
    <button type="button" class="btn btn-outline-primary" onclick="window.location.href = '/Grupos/Index'">Voltar</button>
    </div>
    </div>

    </div>
    </div>
    }

    
    

    I'm still not sending to save on the controller because I am not passing the value of shownlist in the alert, I'm still testing this plugin,

    Friday, October 25, 2019 8:03 PM

Answers

  • User-17257777 posted

    Hi ecocash,

    Debug with F12 Sources panel to analyze the "shownlist" , then get the data from it. Test with the follosing codes:

    $('#btn-salvar').click(function () {
                var cnpjs = $('#shownlist')[0].children;
                var a = $('#shownlist').ready();
                for (i = 0; i < cnpjs.length; i++){
                    var x = cnpjs[i].firstChild.data;
                    var y = x.split(" |")[0];
                    alert(y);
                }
                //alert(cnpjs);
            });

    Result:

    After getting these values, you can put them in an array and pass it to controller with ajax.

    Best Regards,

    Jiadong Meng

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, October 28, 2019 3:25 AM
  • User-733224187 posted

    I got it that way

    viewCreate

    @model mia.Models.Grupo
    
    @{
        ViewBag.Title = "Novo Grupo";
        Layout = "~/Views/Shared/_Layout.cshtml";
    
    
    
    }
    
    
    
    @section Scripts {
    
    
        <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"
                integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo"
                crossorigin="anonymous">
        </script>
        <link rel="stylesheet" href="~/Content/Fancymegatags/fancymetags.css">
    
        <script src="~/Scripts/Fancymegatags/fancymetags.jQuery.js"></script>
    
        <script>
            $('#btn-salvar').click(function () {
                var cnpjs = $('#shownlist')[0].children;
                var listaCpnjs = '';
                var nome_grupo = $('#nome_grupo').val();
    
                for (i = 0; i < cnpjs.length; i++) {
                    var x = cnpjs[i].firstChild.data;
                    var y = x.split(" |")[0];
                    listaCpnjs = listaCpnjs  + y + ',';
                }
    
                listaCpnjs = listaCpnjs.split("/").join("");
                listaCpnjs = listaCpnjs.split(".").join("");
                listaCpnjs = listaCpnjs.split("-").join("");
                 
                window.location.href = "/Grupos/AddGrupo?nome_grupo=" + nome_grupo + "&cnpjs=" + listaCpnjs;
            });
    
        </script>
        <script>
            //$(function () {
            //    $("#tagfield").fancymetags({
            //        theme: "blue",
    
            //    });
            //});
    
    
            function getTags() {//Gets array of existing tags
                var alltags = new Array();
                var i = 0;
                $(".fancyme-tags #shownlist span").each(function (index) {
                    alltags[i] = $(this).html().substr(0, $(this).html().length - 20);
                    i++;
                });
                return alltags;
            };
    
            function setTags() {//Gets string of existing tags separated by commas
                var texttags = getTags();
                var finaltext = "";
                for (var i = 0; i < texttags.length; i++) {
                    if (finaltext == "") {
                        finaltext = texttags[i];
                    }
                    else {
                        finaltext = finaltext + "," + texttags[i];
                    }
                }
                return finaltext;
            }
    
            function addTags() {
                var tags = $(".fancyme-tags input[type=text]").val().trim();
                var listnews = "";
                var newtags = "";
                var existenttags = getTags();
                //checks if a comma was left alone at the end and removes it
                if (tags.substr(tags.length - 1) == ",") {
                    tags = tags.substr(0, tags.length - 1);
                }
                //checks if a comma was left alone at the beginning and removes it
                if (tags.substr(0, 1) == ",") {
                    tags = tags.substr(1, tags.length);
                }
                //if more than one tag was added
                if (tags.indexOf(",") !== -1) {
                    var artags = tags.split(',');
                    for (var i = 0; i < artags.length; i++) {
                        if ((artags[i].trim() !== "") && ($.inArray(artags[i].trim(), existenttags) == -1)) {
                            listnews = listnews + '<span>' + artags[i].trim() + ' | <a href="#">x</a></span>';
                            existenttags.push(artags[i].trim());
                        }
                    }
                }
                //else if just one tag was added
                else {
                    if ($.inArray(tags, existenttags) == -1) {
                        listnews = '<span>' + tags + ' | <a href="#">x</a></span>';
                    }
                }
                //adds everything to the html and clears the value of the textfield
                $(".fancyme-tags #shownlist").append(listnews);
                $(".fancyme-tags input[type=text]").val("");
                $(".fancyme-tags #hiddenlist").html(setTags());
            };
            //event listeners for button and for the enter keypress
            $(".fancyme-tags input[type=button]").click(addTags);
            $(".fancyme-tags input[type=text]").keypress(function (e) {
                if (e.which == 13) {
                    addTags();
                }
            });
            //erase event binding for the Xs in each tag
            $(document).on('click', '.fancyme-tags #shownlist span a', function () {
                event.preventDefault();
                var btn = $(this);
                var hiddens = $(".fancyme-tags #hiddenlist").text();
                var tag = btn.parent().html().toString();
                tag = tag.substr(0, tag.length - 20);
                btn.parent().remove();
                $(".fancyme-tags #hiddenlist").html(setTags());
            });
        </script>
        <script type="text/javascript">
    
    
            function mascaraMutuario(o, f) {
                v_obj = o
                v_fun = f
                setTimeout('execmascara()', 1)
            }
    
            function execmascara() {
                v_obj.value = v_fun(v_obj.value)
            }
    
            function Cnpj(v) {
    
                //Remove tudo o que não é dígito
                v = v.replace(/\D/g, "")
    
                if (v.length <= 14) { //CPj
    
    
    
                    //Coloca ponto entre o segundo e o terceiro dígitos
                    v = v.replace(/^(\d{2})(\d)/, "$1.$2")
    
                    //Coloca ponto entre o quinto e o sexto dígitos
                    v = v.replace(/^(\d{2})\.(\d{3})(\d)/, "$1.$2.$3")
    
                    //Coloca uma barra entre o oitavo e o nono dígitos
                    v = v.replace(/\.(\d{3})(\d)/, ".$1/$2")
    
                    //Coloca um hífen depois do bloco de quatro dígitos
                    v = v.replace(/(\d{4})(\d)/, "$1-$2")
    
                }
    
                return v
    
            }
    
    
        </script>
        
    
    }
    
    @using (Html.BeginForm())
    {
        @Html.AntiForgeryToken()
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-horizontal">
            <h4> Novo Grupo Empresarial </h4>
            <hr />
            <form>
                <div class="container">
                    <div class="row" style="margin-bottom:10px;">
                        <label class="control-label col-md-2">Nome do Grupo</label>
    
                        <div class="col-11" style="padding-right:0px; padding-bottom:5px">
    
                            <input type="text" id="nome_grupo" class="form-control" required data-val="true" name="nome_grupo">
    
                        </div>
    
                    </div>
    
                    <div class="form-group">
                        <label>CNPJ</label>
                        <div class="row  blue fancyme-tags" id="tagfield">
                            <div class='col-10' style='padding-right: 0px;'><input type='text' onkeypress="mascaraMutuario(this, Cnpj)" onblur="clearTimeout()"  maxlength="18" data-val="true" name="cnpj" /><div id='shownlist'></div><div id='hiddenlist'></div></div>
                            <div class='col-2' style='padding-left:0'><input class='btn btn-outline-primary btn-md' type='button' value='Adicionar' id='btn-adicionar' /></div>
                        </div>
                    </div>
    
    
    
                    <div class="row">
                        <div class="col">
                            <button type="button" class="btn  btn-outline-success" id="btn-salvar" onclick="RemoveMaskAndSubmit()">Salvar</button>
                            <button type="button" class="btn  btn-outline-primary" onclick="window.location.href = '/Grupos/Index'">Voltar</button>
                        </div>
                    </div>
    
                </div>
            </form>
        </div>
    }
    

    controller create:

     // GET: Grupos/Create
            public ActionResult Create()
            {
                return View();
            }
    
           
            public ActionResult AddGrupo(string nome_grupo, string cnpjs)
            {
                cnpjs = cnpjs.Substring(0, cnpjs.Length - 1);
    
                cnpjs = cnpjs.Replace("[", string.Empty).Replace("]", string.Empty).Replace("\"", string.Empty);
                string[] obj_cnpjs = cnpjs.Split(',');
    
                Grupo grupo = new Grupo();
    
                grupo.nome_grupo = nome_grupo;
                grupo.cnpjTinyid = new List<Cliente_TinyId_CNPJ>();
    
                foreach (var item in obj_cnpjs)
                {
    
                    var cnpj = item.Split(',')[0];
    
                    var first = cnpj.Substring(0, 2);
                    var second = cnpj.Substring(2, 3);
                    var third = cnpj.Substring(5, 3);
                    var forth = cnpj.Substring(8, 4);
                    var fifth = cnpj.Substring(12, 2);
    
                    var masked_cnpj = first + "." + second + "." + third + "/" + forth + "-" + fifth;
    
                    cnpj = masked_cnpj;
    
                    var tinyCnpj = db.Cliente_TinyId_CNPJ.Where(m => m.cnpj.Equals(cnpj)).FirstOrDefault();
    
                    if (tinyCnpj != null)
                    {
                        grupo.cnpjTinyid.Add(tinyCnpj);
                    }
    
                }
    
    
                if (ModelState.IsValid)
                {
    
                    db.Grupoes.Add(grupo);
                    db.SaveChanges();
                    return RedirectToAction("Index");
                }
    
                return View(grupo);
            }

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, October 28, 2019 8:10 PM

All replies

  • User-17257777 posted

    Hi ecocash,

    Debug with F12 Sources panel to analyze the "shownlist" , then get the data from it. Test with the follosing codes:

    $('#btn-salvar').click(function () {
                var cnpjs = $('#shownlist')[0].children;
                var a = $('#shownlist').ready();
                for (i = 0; i < cnpjs.length; i++){
                    var x = cnpjs[i].firstChild.data;
                    var y = x.split(" |")[0];
                    alert(y);
                }
                //alert(cnpjs);
            });

    Result:

    After getting these values, you can put them in an array and pass it to controller with ajax.

    Best Regards,

    Jiadong Meng

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, October 28, 2019 3:25 AM
  • User-733224187 posted

    Hi jiadongm, would you have an example of how to use Ajax to send in the contreller?

    Monday, October 28, 2019 12:47 PM
  • User-733224187 posted

    I got it that way

    viewCreate

    @model mia.Models.Grupo
    
    @{
        ViewBag.Title = "Novo Grupo";
        Layout = "~/Views/Shared/_Layout.cshtml";
    
    
    
    }
    
    
    
    @section Scripts {
    
    
        <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"
                integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo"
                crossorigin="anonymous">
        </script>
        <link rel="stylesheet" href="~/Content/Fancymegatags/fancymetags.css">
    
        <script src="~/Scripts/Fancymegatags/fancymetags.jQuery.js"></script>
    
        <script>
            $('#btn-salvar').click(function () {
                var cnpjs = $('#shownlist')[0].children;
                var listaCpnjs = '';
                var nome_grupo = $('#nome_grupo').val();
    
                for (i = 0; i < cnpjs.length; i++) {
                    var x = cnpjs[i].firstChild.data;
                    var y = x.split(" |")[0];
                    listaCpnjs = listaCpnjs  + y + ',';
                }
    
                listaCpnjs = listaCpnjs.split("/").join("");
                listaCpnjs = listaCpnjs.split(".").join("");
                listaCpnjs = listaCpnjs.split("-").join("");
                 
                window.location.href = "/Grupos/AddGrupo?nome_grupo=" + nome_grupo + "&cnpjs=" + listaCpnjs;
            });
    
        </script>
        <script>
            //$(function () {
            //    $("#tagfield").fancymetags({
            //        theme: "blue",
    
            //    });
            //});
    
    
            function getTags() {//Gets array of existing tags
                var alltags = new Array();
                var i = 0;
                $(".fancyme-tags #shownlist span").each(function (index) {
                    alltags[i] = $(this).html().substr(0, $(this).html().length - 20);
                    i++;
                });
                return alltags;
            };
    
            function setTags() {//Gets string of existing tags separated by commas
                var texttags = getTags();
                var finaltext = "";
                for (var i = 0; i < texttags.length; i++) {
                    if (finaltext == "") {
                        finaltext = texttags[i];
                    }
                    else {
                        finaltext = finaltext + "," + texttags[i];
                    }
                }
                return finaltext;
            }
    
            function addTags() {
                var tags = $(".fancyme-tags input[type=text]").val().trim();
                var listnews = "";
                var newtags = "";
                var existenttags = getTags();
                //checks if a comma was left alone at the end and removes it
                if (tags.substr(tags.length - 1) == ",") {
                    tags = tags.substr(0, tags.length - 1);
                }
                //checks if a comma was left alone at the beginning and removes it
                if (tags.substr(0, 1) == ",") {
                    tags = tags.substr(1, tags.length);
                }
                //if more than one tag was added
                if (tags.indexOf(",") !== -1) {
                    var artags = tags.split(',');
                    for (var i = 0; i < artags.length; i++) {
                        if ((artags[i].trim() !== "") && ($.inArray(artags[i].trim(), existenttags) == -1)) {
                            listnews = listnews + '<span>' + artags[i].trim() + ' | <a href="#">x</a></span>';
                            existenttags.push(artags[i].trim());
                        }
                    }
                }
                //else if just one tag was added
                else {
                    if ($.inArray(tags, existenttags) == -1) {
                        listnews = '<span>' + tags + ' | <a href="#">x</a></span>';
                    }
                }
                //adds everything to the html and clears the value of the textfield
                $(".fancyme-tags #shownlist").append(listnews);
                $(".fancyme-tags input[type=text]").val("");
                $(".fancyme-tags #hiddenlist").html(setTags());
            };
            //event listeners for button and for the enter keypress
            $(".fancyme-tags input[type=button]").click(addTags);
            $(".fancyme-tags input[type=text]").keypress(function (e) {
                if (e.which == 13) {
                    addTags();
                }
            });
            //erase event binding for the Xs in each tag
            $(document).on('click', '.fancyme-tags #shownlist span a', function () {
                event.preventDefault();
                var btn = $(this);
                var hiddens = $(".fancyme-tags #hiddenlist").text();
                var tag = btn.parent().html().toString();
                tag = tag.substr(0, tag.length - 20);
                btn.parent().remove();
                $(".fancyme-tags #hiddenlist").html(setTags());
            });
        </script>
        <script type="text/javascript">
    
    
            function mascaraMutuario(o, f) {
                v_obj = o
                v_fun = f
                setTimeout('execmascara()', 1)
            }
    
            function execmascara() {
                v_obj.value = v_fun(v_obj.value)
            }
    
            function Cnpj(v) {
    
                //Remove tudo o que não é dígito
                v = v.replace(/\D/g, "")
    
                if (v.length <= 14) { //CPj
    
    
    
                    //Coloca ponto entre o segundo e o terceiro dígitos
                    v = v.replace(/^(\d{2})(\d)/, "$1.$2")
    
                    //Coloca ponto entre o quinto e o sexto dígitos
                    v = v.replace(/^(\d{2})\.(\d{3})(\d)/, "$1.$2.$3")
    
                    //Coloca uma barra entre o oitavo e o nono dígitos
                    v = v.replace(/\.(\d{3})(\d)/, ".$1/$2")
    
                    //Coloca um hífen depois do bloco de quatro dígitos
                    v = v.replace(/(\d{4})(\d)/, "$1-$2")
    
                }
    
                return v
    
            }
    
    
        </script>
        
    
    }
    
    @using (Html.BeginForm())
    {
        @Html.AntiForgeryToken()
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-horizontal">
            <h4> Novo Grupo Empresarial </h4>
            <hr />
            <form>
                <div class="container">
                    <div class="row" style="margin-bottom:10px;">
                        <label class="control-label col-md-2">Nome do Grupo</label>
    
                        <div class="col-11" style="padding-right:0px; padding-bottom:5px">
    
                            <input type="text" id="nome_grupo" class="form-control" required data-val="true" name="nome_grupo">
    
                        </div>
    
                    </div>
    
                    <div class="form-group">
                        <label>CNPJ</label>
                        <div class="row  blue fancyme-tags" id="tagfield">
                            <div class='col-10' style='padding-right: 0px;'><input type='text' onkeypress="mascaraMutuario(this, Cnpj)" onblur="clearTimeout()"  maxlength="18" data-val="true" name="cnpj" /><div id='shownlist'></div><div id='hiddenlist'></div></div>
                            <div class='col-2' style='padding-left:0'><input class='btn btn-outline-primary btn-md' type='button' value='Adicionar' id='btn-adicionar' /></div>
                        </div>
                    </div>
    
    
    
                    <div class="row">
                        <div class="col">
                            <button type="button" class="btn  btn-outline-success" id="btn-salvar" onclick="RemoveMaskAndSubmit()">Salvar</button>
                            <button type="button" class="btn  btn-outline-primary" onclick="window.location.href = '/Grupos/Index'">Voltar</button>
                        </div>
                    </div>
    
                </div>
            </form>
        </div>
    }
    

    controller create:

     // GET: Grupos/Create
            public ActionResult Create()
            {
                return View();
            }
    
           
            public ActionResult AddGrupo(string nome_grupo, string cnpjs)
            {
                cnpjs = cnpjs.Substring(0, cnpjs.Length - 1);
    
                cnpjs = cnpjs.Replace("[", string.Empty).Replace("]", string.Empty).Replace("\"", string.Empty);
                string[] obj_cnpjs = cnpjs.Split(',');
    
                Grupo grupo = new Grupo();
    
                grupo.nome_grupo = nome_grupo;
                grupo.cnpjTinyid = new List<Cliente_TinyId_CNPJ>();
    
                foreach (var item in obj_cnpjs)
                {
    
                    var cnpj = item.Split(',')[0];
    
                    var first = cnpj.Substring(0, 2);
                    var second = cnpj.Substring(2, 3);
                    var third = cnpj.Substring(5, 3);
                    var forth = cnpj.Substring(8, 4);
                    var fifth = cnpj.Substring(12, 2);
    
                    var masked_cnpj = first + "." + second + "." + third + "/" + forth + "-" + fifth;
    
                    cnpj = masked_cnpj;
    
                    var tinyCnpj = db.Cliente_TinyId_CNPJ.Where(m => m.cnpj.Equals(cnpj)).FirstOrDefault();
    
                    if (tinyCnpj != null)
                    {
                        grupo.cnpjTinyid.Add(tinyCnpj);
                    }
    
                }
    
    
                if (ModelState.IsValid)
                {
    
                    db.Grupoes.Add(grupo);
                    db.SaveChanges();
                    return RedirectToAction("Index");
                }
    
                return View(grupo);
            }

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, October 28, 2019 8:10 PM