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
you have the Controller done? and you want to send all emails?
– novic