quarta-feira, 29 de outubro de 2014

Utilizando modal dialog no bootstrap

1. Na pasta “Models” crie ou altere a classe “Pessoa” para o seguinte conteúdo:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
 
namespace ProjetoIESB.Models
{
public class Pessoa
{
[Key]
public int PessoaID { get; set; }
 
[Required(ErrorMessage = "O Nome é obrigatório.")]
public string Nome { get; set; }
 
public int? Idade { get; set; }
}
}

2. No arquivo “Models/IdentityModels.cs”, classe “ApplicationDbContext” verificar se existe a linha abaixo. Caso não exista adicioná-la:
using Microsoft.AspNet.Identity.EntityFramework;
using System;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;
namespace ProjetoIESB.Models
{
// You can add profile data for the user by adding more properties to your ApplicationUser class, please visit http://go.microsoft.com/fwlink/?LinkID=317594 to learn more.
public class ApplicationUser : IdentityUser
{
}
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("DefaultConnection")
{
}
public virtual IDbSet<Pessoa> Pessoas { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
if (modelBuilder == null)
{
throw new ArgumentNullException("modelBuilder");
}
// Desligar o comando de Pluralizacao
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
//Ao desligar a pluralizacao temos um erro grave na definicao das chaves das entidades utilizadas pelo Asp.Identity. Para corrigir isso torna-se necessario reconfigurar estas entidades conforme abaixo:
modelBuilder.Entity<IdentityUserLogin>().HasKey<string>(l => l.UserId);
modelBuilder.Entity<IdentityRole>().HasKey<string>(r => r.Id);
modelBuilder.Entity<IdentityUserRole>().HasKey(r => new { r.RoleId, r.UserId });
}
}
}

3. Executar no Package Manager Console:
PM> Enable-Migrations
PM> add-migration versao1
PM> Update-database

4. Clicar com o botão direito na pasta “Controllers” -> “Add” -> ”Controller” -> “MVC 5 Controller with views, using Entity Framework”.

5. Em “ControllerName” informar “PessoaController”. Em “Model class” selecionar “Pessoa (ProjetoIESB.Models)” e em “Data context class” selecionar “ApplicationDbContext (ProjetoIESB.Models)”. Por fim, clique em “Add”

6. Dentro da pasta “View/Pessoa” edite o arquivo “Index.cshtml”
@model IEnumerable<ProjetoIESB.Models.Pessoa>
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>
@Html.ActionLink("Create New", "Create", null, new { @class = "btn btn-primary btn-lg", data_toggle = "modal", data_target = "#myModal" })
</p>
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"></div>
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.Nome)
</th>
<th>
@Html.DisplayNameFor(model => model.Idade)
</th>
<th></th>
</tr>
 
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.Nome)
</td>
<td>
@Html.DisplayFor(modelItem => item.Idade)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id = item.PessoaID }, new { @class = "btn btn-primary btn-lg", data_toggle = "modal", data_target = "#myModal" }) |
@Html.ActionLink("Details", "Details", new { id = item.PessoaID }, new { @class = "btn btn-primary btn-lg", data_toggle = "modal", data_target = "#myModal" }) |
@Html.ActionLink("Delete", "Delete", new { id = item.PessoaID }, new { @class = "btn btn-primary btn-lg", data_toggle = "modal", data_target = "#myModal" })
</td>
</tr>
}
</table>


7. Edite os arquivos Edit.chsmtl, Create.cshtml, Details.cshtml e Delete.cshtml e insira:
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
<h4 class="modal-title" id="myModalLabel">Modal title</h4>
</div>
<div class="modal-body">

<!-- Deixe aqui o código original da página -->

</div>
<div class="modal-footer">
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")

}

Dicas do EntityFramework

  1. Para recriar o arquivo do banco de dados execute no Package Manager Console (Tools –> Library Package Manager –> Package Manager Console):
# sqllocaldb.exe stop v11.0
# sqllocaldb.exe delete v11.0
# Update-Database
Outra forma:
# Update-Database -TargetMigration: $InitialDatabase
# Update-Database

  1. Comand Reference

  1. Para ajuda:
# get-help Get-Migrations -examples
# get-help Get-Migrations -detailed

# get-help Get-Migrations -full

Utilizando o JQuery.UI e o JQuery.Inputmask no MVC 5


1. Abra o Visual Studio 2013. No menu superior clique em “File” -> “New” -> “Project”. Selecione “Visual C”# -> “ASP.Net Web Application”. Em “Name” escreva “ProjetoIESB” e clique em OK. Na próxima janela, em “Select template”, selecione “MVC” e marque a opção “Add unit tests”. Clique em OK.

2. Instalar o JQuery.UI utilizando o “Package Manager Console”
PM> Install-Package jquery.ui.combined

3. Instalar os scripts  de internacionalização do JQuery utilizando o “Package Manager Console”
PM> Install-Package jQuery.UI.i18n

4. Instalar o script  jquery.inputmask utilizando o “Package Manager Console”
PM> install-package jquery.inputmask

5. Clique com o botão direito na pasta “Scripts” -> “Add” -> “Javascript File”. Em “item name” digite “Site”.

6. Adicione ao final do arquivo App_Start/BundleConfig.cs
bundles.Add(new ScriptBundle("~/bundles/site").Include(
"~/Scripts/Site.js"));
bundles.Add(new ScriptBundle("~/bundles/jqueryui").Include(
"~/Scripts/jquery-ui-{version}.js",
"~/Scripts/jquery.inputmask/jquery.inputmask.js",
"~/Scripts/jquery-ui-i18n.js"));
bundles.Add(new StyleBundle("~/Content/themes/base/css").Include(
"~/Content/themes/base/all.css"));

7. Altere no início do arquivo Views/Shared/_Layout.cshtml
@Styles.Render("~/Content/css")
@Styles.Render("~/Content/themes/base/css")
@Scripts.Render("~/bundles/modernizr")


8. Altere no fim do arquivo Views/Shared/_Layout.cshtml
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/bootstrap")
@Scripts.Render("~/bundles/jqueryui")
@Scripts.Render("~/bundles/site")
@RenderSection("scripts", required: false)

9. Para testar, insira no final do arquivo Views/Home/Index.cshtml
<p>Telefone: <input type="text" id="telefone" /></p>
<p>Data: <input type="text" id="calendario" /></p>
@section Scripts {
<script>
$(document).ready(function () {
$("#telefone").inputmask("mask", { "mask": "(99)99999-9999" });
var lang = window.navigator.userLanguage || window.navigator.language;
lang = lang.substring(0, 2);
$("#calendario").datepicker();
$.datepicker.setDefaults($.datepicker.regional[lang]);
});
</script>
}


10. Outra Forma de utilizar estes componentes é:
<div class="form-group">
@Html.LabelFor(model => model.DataCriacao, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.TextBoxFor(model => model.DataCriacao, new { @class = "date-picker" })
@Html.ValidationMessageFor(model => model.DataCriacao)
</div>

</div>