Arquivo da tag: jquery

Criando um sistema básico de Short Url (parte 2)

Criando um sistema básico de Short Url (parte 2)

Criando um sistema básico de Short Url (parte 2)

Depois de vários meses usando o sistema e tendo que atualizar a lista de links manualmente no XML via FTP, decidi que era hora de melhorar o sistema para que incluísse um banco de dados e um meio de incluir, editar e remover links online.

Portanto, melhorei o sistema e hoje está disponível em http://puul.ga

 

O código fonte (open source) está disponível no Github

Foram feitas várias melhorias no sistema, de forma a ser responsivo e fácil de usar. Mas seu visual e utilidades continuam simples. Cria-se um short link (mesmo conceito que bit.ly) que pode ser compartilhado em qualquer lugar, deixando o link curto e fácil de ser digitado.

O projeto continua sendo em C#, MVC, Entity Framework, Html5, Css3 e jQuery (Bootstrap)

Primeiramente, é necessário criar o objeto/classe que irá conter os dados do Link gerado:

using System;
using System.ComponentModel.DataAnnotations;

namespace Shorten_Urls.Models
{
    public class Url
    {
        public int Id { get; set; }
        [RegularExpression(@"^.{8,}$", ErrorMessage = "Minimum 8 characters required")]
        [Required(ErrorMessage = "Required")]
        [StringLength(30, MinimumLength = 8, ErrorMessage = "Invalid")]
        [Display(Name ="Shareable Url")]
        public string Src { get; set; }
        [Url]
        [Display(Name = "Redirects To")]
        public string Redirect { get; set; }
        public string UserId { get; set; }
        [Display(Name = "Created By")]
        public string Username { get; set; }
        //[DataType(DataType.Date)]
        //[DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}", ApplyFormatInEditMode = true)]
        [Display(Name = "Created On")]
        public DateTime CreatedOn { get; set; }
        //[DataType(DataType.Date)]
        //[DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}", ApplyFormatInEditMode = true)]
        [Display(Name = "Expires")]
        public DateTime? Expires { get; set; }
    }
}

Também é necessário criar o Repositório (ou Data Layer). Esse repositório permite o uso tanto de XML quanto SQL, sendo configurada a opção no

web.config
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using Microsoft.AspNet.Identity;
using System.Configuration;
using System.Data.Entity;

namespace Shorten_Urls.Models
{
    public class UrlRepository : IRepository<Url>
    {
        private XDocument _urls;
        private List<Url> urls;
        ApplicationDbContext _context;
        private readonly string DbProvider = ConfigurationManager.AppSettings["DbProvider"];
        private const string SQL = "Sql";
        private const string XML = "Xml";
        public bool needLastId { get { return DbProvider.Equals(XML); } }

        public List<Url> Urls { get { return urls; } }
        public int LastId
        { get { return urls.Last().Id; } }

        public UrlRepository()
        {
            urls = new List<Url>();

            if (DbProvider == XML)
            {
                _urls = MvcApplication.IO.Forwards;

                IEnumerable<XElement> rootDescendants = _urls.Descendants("url");
                foreach (XElement e in rootDescendants)
                    urls.Add(MapXElement(e));
            }
            else if (DbProvider == SQL)
            {
                _context = new ApplicationDbContext();
                urls = _context.Forwarders.ToList();
            }
        }

        public bool Exists(string src)
        {
            var yes = from y in urls where y.Src == src select y;
            if (yes.Count() > 0) return true;
            else return false;
        }

        public IEnumerable<Url> GetAll()
        {
            return urls;
        }

        public void Add(Url url)
        {
            urls.Add(url);
            if (DbProvider == XML)
                MvcApplication.IO.AddForward(url);
            else if (DbProvider == SQL)
            {
                _context.Forwarders.Add(url);
                _context.SaveChanges();
            }
        }
        public Url GetById(int Id)
        {
            Url e = (from url in urls where url.Id == Id select url).Single();
            if (DbProvider == SQL)
            {
                PopulateUsername(e);
            }
            return e;
        }
        public List<Url> GetByUserId(string userId)
        {
            List<Url> list = (from urlList in urls where urlList.UserId == userId select urlList).ToList();
            if (DbProvider == SQL)
            {
                foreach (Url url in list) PopulateUsername(url);
            }
            return list;
        }
        public Url GetBySrc(string src)
        {
            var e = (from url in urls where url.Src.Equals(src) select url);
            if (e.Count() == 0) return null;
            else {
                if (DbProvider == SQL)
                {
                    PopulateUsername(e.Single());
                }
                return e.Single();
            }
        }

        public void Remove(int id)
        {
            Url remove = (from url in urls where url.Id == id select url).Single();
            urls.Remove(remove);
            Remove(remove);
        }

        public void Remove(Url url)
        {
            urls.Remove(url);
            if (DbProvider == XML)
                MvcApplication.IO.RemoveForward(url);
            else if (DbProvider == SQL)
            {
                _context.Forwarders.Remove(url);
                _context.SaveChanges();
            }
        }

        public void Remove(string src)
        {
            Url remove = (from url in urls where url.Src == src select url).Single();
            urls.Remove(remove);
            Remove(remove);
        }

        public void RemoveAll()
        {
            urls.Clear();
        }

        public void RemoveByUserId(string userId)
        {
            Url remove = (from url in urls where url.UserId == userId select url).Single();
            urls.Remove(remove);
            Remove(remove);
        }

        public void Update(Url url)
        {
            Url old = (from urlE in urls where urlE.Id == url.Id select urlE).Single();
            urls.Remove(old);
            urls.Add(url);
            if (DbProvider == XML)
            {

                MvcApplication.IO.RemoveForward(old);
                MvcApplication.IO.AddForward(url);
            }
            else if (DbProvider == SQL)
            {
                _context.Entry(url).State = EntityState.Modified;
                _context.SaveChanges();
            }
        }


        private Url PopulateUsername(int id)
        {
            Url url = (from u in urls where u.Id == id select u).Single();
            string userId = url.UserId == null ? "" : url.UserId;
            UserRepository userRepo = new UserRepository();
            url.Username = userRepo.GetUsername(userId);
            return url;
        }
        private Url PopulateUsername(Url url)
        {
            UserRepository userRepo = new UserRepository();
            string userId = url.UserId == null ? "" : url.UserId;
            url.Username = userRepo.GetUsername(userId);
            return url;
        }
        private Url MapXElement(XElement element)
        {
            DateTime expires = element.Attribute("expires").Value == "" ? new DateTime(2999, 12, 31) : DateTime.Parse(element.Attribute("expires").Value);
            DateTime createdOn = element.Attribute("created").Value == "" ? DateTime.Now : DateTime.Parse(element.Attribute("created").Value);
            string userId = element.Attribute("userid").Value;
            int id = int.Parse(element.Attribute("id").Value);
            Url url = new Url
            {
                Id = id,
                CreatedOn = createdOn,
                Expires = expires,
                UserId = userId,
                Redirect = element.Value.Trim(),
                Src = element.Attribute("src").Value
            };
            return PopulateUsername(url);
        }
    }
}

A parte mais importante do projeto é o Controller que vai servir os Links, e as rotas de leitura dos links. Portanto, o

RouteConfig.cs

também tem que estar correto:

ForwardsController.cs
using Shorten_Urls.Models;
using System;
using System.Collections.Generic;
using System.Web.Mvc;
using System.Web.Script.Serialization;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;

namespace Shorten_Urls.Controllers
{
    public class ForwardsController : Controller
    {
        private UrlRepository _repo;
        private UserRepository _usersRepo;
        private ApplicationUser user;

        public ForwardsController()
        {
            _repo = new UrlRepository();
            _usersRepo = new UserRepository();
        }
        //
        // GET: /Forwards/

        public ActionResult SendToSrc(string src)
        {
            string error404 = "404.html";
            string redirect = "/Home/Index";

            Url url = _repo.GetBySrc(src);
            if (url != null)
            {

                if (!url.Redirect.Equals(string.Empty) && (url.Expires > DateTime.Now || url.Expires == null))
                    redirect = url.Redirect;
                else
                    redirect = error404;
            }
            return Redirect(redirect);
        }
        [Authorize]
        public ActionResult List()
        {

            List<Url> urls;
            if (User != null)
                user = _usersRepo.GetById(User.Identity.GetUserId());

            if (user.UserType == UserTypes.Administrator)
                urls = _repo.Urls;
            else urls = _repo.GetByUserId(user.Id);

            return View(urls);
        }

        //
        // GET: /Forwards/Details/5
        [Authorize]

        public ActionResult Details(int id)
        {
            if (User != null)
                user = _usersRepo.GetById(User.Identity.GetUserId());

            if (id == 0)
                Redirect("/Home/Index");
            Url url = _repo.GetById(id);
            return View(url);
        }

        //
        // GET: /Forwards/Create
        [Authorize]

        public ActionResult Create()
        {
            if (User != null)
                user = _usersRepo.GetById(User.Identity.GetUserId());

            Url url = new Url();
            string random = Helpers.GenerateRandomgUrl();
            while (_repo.Exists(random))
            {
                random = Helpers.GenerateRandomgUrl();
            }
            ViewBag.RandomUrl = random;
            return View(url);
        }

        [HttpGet]
        public string Available(string Src)
        {
            bool exists = _repo.Exists(Src);
            return new JavaScriptSerializer().Serialize(!exists);
        }
        //
        // POST: /Forwards/Create

        [Authorize]
        [HttpPost]
        public ActionResult Create(string Redirect, string Src, DateTime? Expires)
        {
            try
            {
                // TODO: Add insert logic here
                if (User != null)
                    user = _usersRepo.GetById(User.Identity.GetUserId());

                Url newUrl = new Url
                {
                    Redirect = Redirect,
                    Src = Src,
                    CreatedOn = DateTime.Now,
                    Expires = Expires,
                    UserId = user.Id,
                    Username = _usersRepo.GetUsername(user.Id)
                };

                if (_repo.needLastId)
                    newUrl.Id = _repo.LastId + 1;

                _repo.Add(newUrl);
                TempData["Success"] = "Short Url has been created";
                return RedirectToAction("List");
            }
            catch
            {
                TempData["Error"] = "There was an error saving your new Url";
                return View("List");
            }
        }

        //
        // GET: /Forwards/Edit/5
        [Authorize]

        public ActionResult Edit(int id)
        {
            if (User != null)
                user = _usersRepo.GetById(User.Identity.GetUserId());

            Url editUrl = _repo.GetById(id);
            return View(editUrl);
        }

        //
        // POST: /Forwards/Edit/5
        [Authorize]
        [HttpPost]
        public ActionResult Edit(int Id, string Redirect, string Src, DateTime? Expires = null)
        {
            try
            {
                // TODO: Add update logic here
                if (User != null)
                    user = _usersRepo.GetById(User.Identity.GetUserId());

                Url editUrl = _repo.GetById(Id);
                editUrl.Redirect = Redirect;
                editUrl.Src = Src;
                editUrl.UserId = user.Id;
                editUrl.Expires = Expires;
                editUrl.Username = _usersRepo.GetUsername(user.Id);

                _repo.Update(editUrl);
                TempData["Success"] = "Short Url has been updated";
                return RedirectToAction("List");
            }
            catch
            {
                TempData["Error"] = "There was an error saving your Url";
                return View();
            }
        }

        //
        // GET: /Forwards/Delete/5
        [Authorize]
        public ActionResult Delete(int id)
        {
            if (User != null)
                user = _usersRepo.GetById(User.Identity.GetUserId());
            Url url = _repo.GetById(id);
            return View(url);
        }

        [Authorize]
        [HttpPost]
        public ActionResult Delete(int id, bool confirm)
        {
            try
            {
                if (User != null)
                    user = _usersRepo.GetById(User.Identity.GetUserId());

                _repo.Remove(id);
                TempData["Success"] = "Short Url has been deleted";
                return RedirectToAction("List");

            }
            catch
            {
                TempData["Error"] = "There was an error deleting your Url";
                Url url = _repo.GetById(id);
                return View(url);
            }
        }

    }
}
RouteConfig.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

namespace Shorten_Urls
{
    public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                name: "Forward",
                url: "{src}",
                defaults: new { controller = "Forwards", action = "SendToSrc", src = "" }
                );

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );
        }
    }
}

Ao final, configura-se o

web.config

com as seguintes chaves:

 <appsettings>
    <add key="ForwardsFile" value="~/App_Data/forwards.xml"></add>
    <add key="LenghtOfRandomString" value="8"></add>
    <add key="WebsiteName" value="Puulga"></add>
    <add key="WebsiteUrl" value="http://puul.ga/"></add>
    <add key="Website" value="true"></add>
    <!--email provider section-->
    <add key="siteadmin" value="email@puul.ga"></add>
    <add key="email-subject" value="Email from Puul.ga"></add>
    <add key="email-from" value="email@puul.ga"></add>
    <add key="email-from-name" value="Puul.ga"></add>
    <add key="email-require-auth" value="false"></add>
    <add key="email-username" value="puul.ga"></add>
    <add key="email-password" value="password"></add>
    <add key="email-port" value="3535"></add>
    <add key="useSSL" value="false"></add>
    <add key="email-server" value="localhost"></add>
    <add key="email-html-share" value="~/Email Templates/share.html"></add>
    <add key="email-html-default" value="~/Email Templates/puulga.html"></add>
    <add key="email-html-forgotten" value="~/Email Templates/puulga.html"></add>
    <add key="email-html-confirmation" value="~/Email Templates/puulga.html"></add>
    <add key="email-html-welcome" value="~/Email Templates/puulga.html"></add>
    <!--Database options. possible values: Xml, Sql-->
    <add key="DbProvider" value="Sql"></add>
  </appsettings>

Basicamente, esses são os elementos mais importantes para o funcionamento do projeto. Todo o código fonte está disponível no Github em código aberto.

Visite o site para ver como funciona.

Alerta não Intrusivo

Como criar um Alerta Não Intrusivo

Veja como é fácil criar um alerta não Intrusivo, com algumas poucas linhas de código, criar um alerta que não atrapalha o usuário, e pode ser atualizado de várias formas. Neste exemplo, estou usando um arquivo javascript que contém os alertas (veja abaixo).

  1. Copie o Html que é bastante simples
  2. Copie o CSS que já está bastante completo, mas fique a vontade em modificar
  3. Copie o jQuery (que também pode ser modificado)
  4. Se quiser usar o método de alertas deste demo, copie os alertas
  5. Ou baixe o demo completo em zip

Para este demo, foram usados os seguintes recursos:

 

Veja em ação no demo

Html


<div id="alert">

<div id="close-alert">X</div>

        <span>
            <i class='fa fa-2x' id="alert-icon"></i>
        </span>
        <span id="alert-message"></span>
    </div>

CSS

 #alert {
     z-index: 999;
     position: fixed;
     left: 0;
     width: 100%;
     height: 60px;
     text-align: center;
     padding: 12px 0 30px 0;
     background-color: #000;
     opacity: 0.6;
     color: #fff;
     text-shadow: 0 0 2px #ccc;
     bottom: 0px;
     /*Mude aqui para definir se o 
     alerta vai ser encima ou no rodape; 
     use bottom para rodapé e top para cabeçalho*/
 }
 #alert #close-alert {
     border: 1px solid #000;
     position: absolute;
     right: 0px;
     top: 0;
     color: #fff;
     width: 32px;
     height: 32px;
     line-height: 32px;
     transition: all 0.2s ease;
     cursor: pointer;
 }
 #alert #close-alert:hover {
     background-color: #980000;
     border: 1px solid #fff;
 }
 #alert span {
     max-width: 80%;
 }
 #alert-icon{
     padding-right: 15px
 }
 #alert #alert-message a, #alert #alert-message a:visited{
    color:#c2c2c2;
    font-weight: 800;
    text-decoration: none;
    transition: all 0.2s ease-in;
}
#alert #alert-message a:hover{
    color:#fff;
    text-shadow:0 0 3px #ccc;
}

jQuery

$(function () {

  Rollnews(); //inicia a rolagem de alertas
  
  $("#close-alert").click(function(){
    $("#alert").fadeOut(); //fecha o alerta
  });

});
//Rolagem de alertas
function Rollnews(){
  var i=0;
  $("#alert-icon").addClass(news[i].icon);
  $("#alert-message").html(news[i].text);
  $("#alert-icon,#alert-message").fadeIn();
  setInterval(function(){
    var previous = i;
    i++;
    if(i>news.length-1){
      i = 0;
    }
    $("#alert-icon").removeClass(news[previous].icon).addClass(news[i].icon);
    $("#alert-message").html(news[i].text);
  },3*1000);
}

Alertas

var news = [
        {    
    text : "Este é o primeiro alerta com um &lt;a href='http://www.zueuz.com.br' target='_blank'&gt;Link&lt;/a&gt;", 
    icon : "fa-info-circle"
        },
        {
    text : "Este é o segundo alerta, com outra mensagem qualquer",
    icon : "fa-exclamation-circle"
        },
        {
    text : "Ainda mais um alerta, que pode ser uma mensagem, uma imagem, ou um tweet (tweets necessitam de outro plugin)",
    icon : "fa-bell-o"
        }];

Simples botão de Fechar com CSS3 e Jquery

Simples botão de Fechar com CSS3 e Jquery

Neste artigo, Simples botão de Fechar com CSS3 e Jquery, mostrarei como usar um código simples, ao invés de ficar criando imagens para botões, por quê não criar um somente com CSS3? Sem mais delongas, segue o código:

Html do botão:

	<div id="alert">
		<div class="close">X</div>
		<h1>Aviso</h1>
		<p>Texto do seu alerta</p>
	</div>

CSS3 do botão:

.close{
	width: 24px; /*largura*/
	height: 24px; /*altura*/
	font-size: 8px; /*tamanho da fonte (X)*/
	line-height: 24px; 
/*tamanho da linha que contem o texto - 
24 é o mesmo tamanho do botão para o X 
ficar alinhado no centro (cima-baixo)*/
	text-align: center; /*alinhamento to texto no meio do botão (esq-dir)*/
	position: relative; /*relativo para ficar por posicionado como está 
- acima e para fora da caixa de alerta*/
	right: -288px; /*posição em relação à  linha da caixa de alerta - horizontal*/
	top: -12px; /*posição em relação à  linha da caixa de alerta - vertical*/
	float: left; /*desacopla o botão do resto dos componentes*/
	border-radius: 50%; /*raio de circunferencia dos cantos - 50% faz cada lado ficar totalmente redondo, criando um botão circular*/
	border: 1px solid #ccc; /*borda do botão*/
	background-color: #F55555; /*cor de fundo do botão*/
	color: #000; /*cor do text*/
	transition: all 0.2s ease; /*animação que ocorre quando alguma ação é realizada*/
	cursor: pointer; /*mostra o dedo de link mostrando que é clicável*/
}

Jquery de fechamento:

$('.close').click(function(event){
		$('#alert').fadeOut();
		event.preventDefault();
	});

Download da fonte: botao_fechar

DEMO

Busca específica em texto usando jQuery

Busca específica em texto usando jQuery

Nem todo usuário conhece o atalho ctrl+F (buscar) que está presente em quase todos os apps de hoje em dia.

Por esse motivo, é sempre válido criar uma caixinha de busca em páginas que contém muito texto. Busca específica em texto usando jQuery mostra como alcançar essa funcionalidade.

Busca específica em texto usando jQuery

Para este demo foi usado o jQuery highlight Plugin do Johann Burkard.

HTML

<html>
<head>
  <meta name="robots" content="noindex, nofollow"/>
  <script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
  <script type="text/javascript" src="scripts/page.js"></script>
  <link href='css/style.css' rel="stylesheet" type="text/css"/>
  <title>Busca com JQuery</title>
</head>
<body>
  <div id="keys">
    <div id="searchBox">
      <input type="text" id="txtsearch" placeholder="search" name="search"/>
      <div id="btnsearch" title="Buscar no texto"></div>
      <div class="break"></div>
      <div class='back-top'>inicio &#8593;</div>
    </div>
    <h1>Texto a ser pesquisado</h1>
    <section>
      TEXTO AQUI
    </section>
    <script src="scripts/jquery.highlight-4.closure.js" type="text/javascript"></script>
  </body>
  </html>

CSS

#searchBox{
position: fixed;
top: 0;
right: 0;
width: 190px;
background-color: #000;
box-shadow: 0 0 8px #ccc;
padding: 0 5px 10px 0;
margin: -4px 0 0 0;
border-radius: 4px;
color: #fff;
text-align: right;
}
#searchBox a{
    color:#fff !important;
}
#txtsearch
{
   border: 4px solid #000;
   line-height: 35px;
   font-size: 14px;
   padding-left: 10px;
   font-family: 'Segoe UI';
   border-bottom-right-radius: 8px;
   border-bottom-left-radius: 8px;
   float:left;
   margin-left:5px;
}
#txtsearch:focus{
    outline:none;
}
#btnsearch{
   background:url('../images/search.png') no-repeat center;
   background-size: 24px;
   width: 24px;
   height: 24px;
   float:left;
   cursor: pointer;
   z-index: 999999;
   margin: 10px 0 0 -40px;
}
.highlight { background-color: #F6E8B9; font-weight: bold; }

.back-top{
   color:#fff;
   font-weight: bold;
   padding-left:15%;
   cursor: pointer;
   transition:letter-spacing 0.3s ease;
}
.back-top:hover{
    letter-spacing:3px;
}

#txtsearch
{
   border: 1px solid #000;
   line-height: 18px;
   font-size: 16px;
   padding-left: 10px;
   font-family: 'Segoe UI';
   border-bottom-right-radius: 8px;
   border-bottom-left-radius: 8px;
   float:left;
}
#btnsearch{
   background:url('../images/search.png') no-repeat center;
   background-size: 16px;
   width: 16px;
   height: 16px;
   float:left;
   cursor: pointer;
   z-index: 999999;
   margin: 7px 0 0 -25px;
}

jQuery

 var counter = 0;
 $(function(){
  $('.back-top').click(function(){
   $('html, body').animate({
    scrollTop: 0
  }, 300);
 });

  $("#btnsearch").click(function(e){
    $("body").removeHighlight();
    $("body").highlight($("#txtsearch").val());
    var curr = $('.highlight')[counter];
    var top =  $(curr).offset().top-180;
    $('html, body').animate({
      scrollTop: top
    }, 300);
    counter++;
    if(counter>=$('.highlight').length)counter=0;
  });
  $("#txtsearch").click(function(){
    $(this).select().focus();
  });
  $("#txtsearch").keypress(function(e){
    if(e.which===13) {
      $("#btnsearch").click();
    };
  });

})

Veja o Demo

Código Fonte

Abstraindo Multiplas chamadas jQuery (Ajax)

Abstraindo Multiplas chamadas jQuery (Ajax)

Quando se tem várias chamadas AJAX (jQuery) na mesma página, ou projeto, fica mais fácil abstrair as chamadas de forma que as chamadas na página diminuam a complexidade e possibilidade de erro. Para tal, pode-se criar um método Generico de acordo com o tipo de submissão ajax. Neste caso, usa-se post:

  function  Post(method,  datanames,  data,  callback)  {
                        var  datastring  =  "";

                        var  size  =  $(datanames).size();

                        if  (datanames  !=  null  &&  data  !=  null)  {
                                if  (size  >  0)  {
                                        $(datanames).each(function  (index,  value)  {
                                                datastring  +=  value  +  ":'"  +  data[index]  +  "'";
                                                if  (index  <  size  -  1)  datastring  +=  ",";
                                        });

                                }  else  datastring  =  datanames  +  ":'"  +  data  +  "'";
                        }

                        var  response  =  $.ajax({
                                type:  "POST",
                                url:  page  +  method,
                                data:  "{  "  +  datastring  +  "  }",
                                contentType:  "application/json;  charset=utf-8",
                                dataType:  "json",
                                success:  function  (d)  {
                                        callback(d);
                                }
                        });
                }

Note que os argumentos precisam ser processados, por isso temos que fazer algumas validações no código.

Após a criação do método, é possível fazer uma chamada mais simples, de qualquer outra parte do projeto:

  
  //Nova  tabela  completa
                        $("#btnNovaTabela").click(function  ()  {
                                var  nome,  sobrenome,  pontos,  method;

                                nome  =  $("#txtNome").val();
                                sobrenome  =  $("#txtSobrenome").val();
                                pontos  =  $("#txtPontos").val();
                                method  =  "NovaTabela";

                                var  args  =  [nome,  sobrenome,  pontos];
                                var  argnames  =  ["nome",  "sobrenome",  "pontos"];

                                Post(method,  argnames,  args,  function  (response)  {
                                        $("#conteudo-dinamico-table").append(response.d);
                                        $("input").each(function  ()  {  $(this).val("");  });
                                });
                        });

Faça o download  do código deste exemplo

Faça o download  do código pronto para rodar (unzip em C:\)