How to enter data with JSON and MVC5

Asked

Viewed 263 times

1

I have a registration screen, where the user can insert 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 launch this dynamically generated Save button and pass the entered data to my Model, and this input Row is gone to make way for a label-only Row showing the last added email?

  • you have the Controller done? and you want to send all emails?

2 answers

2


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

Minimal 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 that code of controller just have the same name as input (that in the case was e-mail) to redeem the information and thus make the recording 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 });
        }
    }
}

References

1

Hello,

By your question, your difficulty is in assembling this front-end, so 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>
<div class="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 and made the callback call directly only for the purpose of exemplification. In your application you uncomment ajax and configure the correct url.

  • Thank you Diego , your solution complemented the solution that Virgilio passed. Both helped a lot!

Browser other questions tagged

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