How to insert data with JSON and MVC5

1

I have a registration screen where the user can enter as many emails as he wants in each record. For this, in my View I have the following code

<div class="form-group">
        <button type="button" id="btnAddEmail">Adicionar</button>
        <table id="tblEmails">
            <thead>
                <tr>
                    <td>#</td>
                    <td>Email</td>
                </tr>
            </thead>
            <tbody></tbody>
        </table>
    </div>

$(document).ready(function () {
            $("#btnAddEmail").click(function () {
                $("#tblEmails tbody").append("<tr>" +
                "<td></td>" +
                "<td><input id='txtEmail'></td>" +
                "<td class='bto'><button type='button'>Salvar</button></td></tr>");
            });

When I click Add, a new row appears in the table with the field to insert a new email with the Save button.

How do I trigger this Save button dynamically generated and pass the data entered to my Model, and this row with input disappears to give way to a row with only label showing the last email added?

    
asked by anonymous 21.08.2017 / 22:28

2 answers

2
To make this code, you must construct several javascript one functions to add input , one to save and send Server-Side information, one to replace input with span and another to disappear with the button, I also made a cancel button if you want to cancel the action of creating a new email.

Minimum example:

Code of View :

@{
    ViewBag.Title = "Index";
}
<h2>Index</h2>
<div class="form-group">
    <button type="button" id="btnAddEmail">Adicionar</button>
    <table id="tblEmails">
        <thead>
            <tr>
                <td>#</td>
                <td>Email</td>
            </tr>
        </thead>
        <tbody></tbody>
    </table>
</div>
@section scripts {
    <script>
        var isEmail = function (value)
        {
            var t = /^[a-z0-9.]+@@[a-z0-9]+\.[a-z]+\.([a-z]+)?$/i;
            return t.test(value);
        }
        var uniqid = function () {
            return (new Date().getTime()
                + Math.floor((Math.random() * 10000)
                    + 1)).toString(16);
        };
        function addEmail()
        {
            var id = uniqid();
            var u = 'txt' + id;
            var t = 'tr' + id;
            var s = '<tr id=\'' + t + '\'><td></td>';
            s = s + '<td><input name="email" id="' + u + '" required></td>';
            s = s + '<td class="bto">';
            s = s + '<button type="button" 
                      onclick="saveEmail(\'' + u + '\')">Salvar</button>';
            s = s + '<button type="button" 
                      onclick="cancelEmail(\'' + t + '\')">Cancelar</button>';
            s = s + '</td ></tr>';
            $("#tblEmails tbody").append(s);

        }
        function saveEmail(id) {
            var obj = document.getElementById(id);
            if (obj.value != "" && isEmail(obj.value)) {
                $.post("@Url.Action("Create", "Emails")", { email: obj.value },
                    function (response) {
                        if (response.status) {
                            replaceLabelAndButton(obj);
                        }
                    }, 'json');

                return true;
            }
            alert("Digite o e-mail corretamente");
            obj.focus();
            return false;
        }
        function cancelEmail(id) {
            jQuery(document.getElementById(id)).remove();
        }
        function replaceLabelAndButton(obj) {
            jQuery(obj)
                .parent()
                .next()
                .html('');
            jQuery(obj)
                .parent()
                .html('<span>' + obj.value + '</span>');
        }
        $(document).ready(function () {
            $("#btnAddEmail").click(function () {
                addEmail();
            });
        });
    </script>
}

Code of Controller :

In this code of controller it is only to have the same name as the input ( which in the case was email ) to retrieve the information and thus make the write code. >

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace WebApplication7.Controllers
{
    public class EmailsController : Controller
    {

        public ActionResult Index()
        {
            return View();
        }

        public JsonResult Create(string email)
        {
            var c = email;
            return Json(new { status = true });
        }
    }
}

21.08.2017 / 23:35
1

Hello,

By your question, your difficulty is to mount this front end, then follow an example below:

$(document).ready(function () {
  $("#btnAddEmail").click(function () {
      $("#tblEmails tbody").append("<tr>" +
      "<td></td>" +
      "<td><input name='txtEmail'></td>" +
      "<td><button type='button' class='bt-salvar'>Salvar</button></td></tr>");
  });
  
  // Evento click do botão gerado dinamicamente
  $(document).on('click', '.bt-salvar', function() {
  
    var $tr = $(this).closest('tr');
    
    // Recupera o valor do campo
    var email = $tr.find('[name="txtEmail"]').val();
    
    // Executa o ajax
    /*$.ajax({
      type: "POST",
      url: ".",
      data: {email: email},
      success: callback_success,
      error: function() {
        alert('Falha ao salvar');
      }
    });*/
    callback_success();
    
    function callback_success() {
      alert('Registro salvo com sucesso');
      $tr.remove();
    }
    
  });
});
table {
  width: 100%;
}
table td {
  border: 1px solid #ccc;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divclass="form-group">
    <button type="button" id="btnAddEmail">Adicionar</button>
    <table id="tblEmails">
        <thead>
            <tr>
                <td>#</td>
                <td>Email</td>
                <td>Ação</td>
            </tr>
        </thead>
        <tbody></tbody>
    </table>
</div>

I left the ajax commented out and made the callback call directly for illustration purposes only. In your application you uncomment the ajax and configure the correct url.

    
21.08.2017 / 23:37