Aplicação ASP.NET MVC 4 Usando Banco de Dados



Similar documents
AD A O.N. ET E Access Data Object

Conexión SQL Server C#

ASP.NET Programming with C# and SQL Server

Database Communica/on in Visual Studio/C# using ASP.NET Web Forms. Hans- PeBer Halvorsen, M.Sc.

A PROJECT REPORT ON. SkyDrive. Submitted for the partial fulfillment of the requirement for the Award of the degree of MASTER OF COMPUTER APPLICATION

How To Create A Database In Araba

ADOBE READER AND ACROBAT

5 Airport. Chapter 5: Airport 49. Right-click on Data Connections, then select Add Connection.

Paging, sorting, and searching using EF Code first and MVC 3. Introduction. Installing AdventureWorksLT database. Creating the MVC 3 web application

MS Enterprise Library 5.0 (Logging Application Block)

The MVC Programming Model

İNTERNET TABANLI PROGRAMLAMA- 13.ders GRIDVIEW, DETAILSVIEW, ACCESSDATASOURCE NESNELERİ İLE BİLGİ GÖRÜNTÜLEME

SQL injection attacks SQL injection user input SQL injection SQL Command parameters Database account. SQL injection attacks Data Code

Access Data Object (cont.)

A Tutorial on SQL Server CMPT 354 Fall 2007

Manual Activity after implementing note

Boletim Técnico. Esta implementação consiste em atender a legislação do intercâmbio eletrônico na versão 4.0 adotado pela Unimed do Brasil.

CHAPTER 13 Getting Started with Identity

Brazil + JDBC Juin 2001, douin@cnam.fr

FANESE Faculdade de Administração e Negócios de Sergipe. Tópicos Avançados em Desenvolvimento WEB. Prof.: Fabio Coriolano.

CHAPTER 10: WEB SERVICES

TO HACK AN ASP.NET WEBSITE?

Creating the Product Catalog Part I (continued)

Chair of Software Engineering. Java and C# in depth. Carlo A. Furia, Bertrand Meyer. C#: Persistence

C# Datenbank-Programmierung

Web Programming with PHP 5. The right tool for the right job.

Direct Post Method (DPM) Developer Guide

Classe AGI - PHP 5.x

Implementing a WCF Service in the Real World

1.Tüm Kayıtları Getirme - Arama Yapma

Working with Data in ASP.NET 2.0 :: Creating Stored Procedures and User Defined Functions with Managed Code Introduction

Database Query 1: SQL Basics

USER GUIDE Appointment Manager

Download this chapter for free at:

A Step by Step Guide for Building an Ozeki VoIP SIP Softphone

Database Communica/on in Visual Studio/C# using Web Services. Hans- Pe=er Halvorsen, M.Sc.

ASP.NET(C#) ile Kayıt Listeleme, Silme ve Düzenleme İşlemi

Java Server Pages and Java Beans

Chapter 14 WCF Client WPF Implementation. Screen Layout

Guide to Integrate ADSelfService Plus with Outlook Web App

Implementing Specialized Data Capture Applications with InVision Development Tools (Part 2)

SQL Injection. The ability to inject SQL commands into the database engine through an existing application

The Developer Side of the MS Business Intelligence Stack

Getting Started with Telerik Data Access. Contents

Programming ASP.NET MVC 5

PROCEDURE INSERTION(NUM IN EMPLOYES.NUMEMP%TYPE, NOM VARCHAR2, PRENOM IN VARCHAR2, PPHOTO IN BLOB, SALAIRE IN NUMBER);

PROJECT REPORT OF BUILDING COURSE MANAGEMENT SYSTEM BY DJANGO FRAMEWORK

ASP.NET Dynamic Data

MCSD Azure Solutions Architect [Ativar Portugal] Sobre o curso. Metodologia. Microsoft - Percursos. Com certificação. Nível: Avançado Duração: 78h

See the Developer s Getting Started Guide for an introduction to My Docs Online Secure File Delivery and how to use it programmatically.

Using IRDB in a Dot Net Project

Implementation of the AutoComplete Feature of the Textbox Based on Ajax and Web Service

Using Netbeans and the Derby Database for Projects Contents

ArcHC_3D research case studies (FCT:PTDC/AUR/66476/2006) Casos de estudo do projecto ArcHC_3D (FCT:PTDC/AUR/66476/2006)

Web Design I. Spring 2009 Kevin Cole Gallaudet University

! "#" $ % & '( , -. / 0 1 ' % ' 3" 4569& 7 456: % 9 ; ; <&= 3 %,< & 4 4 % : ' % > ' % ? 1 3 & B&?

v1.1.0 SimpleSQL SQLite manager for Unity3D echo17.com

By : Ashish Modi. CRUD USING PHP (Create, Read, Update and Delete on Database) Create Database and Table using following Sql Syntax.

2009 Tutorial (DB4O and Visual Studio 2008 Express)

MyChartWebPart.cs. // For SortList using System.Collections.Generic; using System.Collections; // For DataTable using System.Data;

How To: Create a Crystal Report from ADO.NET Dataset using Visual Basic.NET

Lab 8: ASP.NET 2.0 Configuration API and Health Monitoring

Entity Framework Documentation

Installing the ASP.NET VETtrak APIs onto IIS 5 or 6

MVC :: Passing Data to View Master Pages

Designing for Dynamic Content

Building a web application with ASP.NET MVC using DocumentDB

Chapter 9 Java and SQL. Wang Yang wyang@njnet.edu.cn

Web Development using PHP (WD_PHP) Duration 1.5 months

listboxgaatmee.dragdrop += new DragEventHandler(listBox_DragDrop); ListBox from = (ListBox)e.Data.GetData(typeof(ListBox));

Database Access from a Programming Language: Database Access from a Programming Language

Database Access from a Programming Language:


A table is a collection of related data entries and it consists of columns and rows.

Designing and Implementing an Online Bookstore Website

DESIGNING HTML HELPERS TO OPTIMIZE WEB APPLICATION DEVELOPMENT

TABLE OF CONTENTS INSTALLATION MANUAL MASTERSAF DW

Integrating Web & DBMS

WHITEPAPER. Skinning Guide. Let s chat Velaro info@velaro.com by Velaro

WEB DESIGN LAB PART- A HTML LABORATORY MANUAL FOR 3 RD SEM IS AND CS ( )

Displaying a Table of Database Data (VB)

Mini Project Report ONLINE SHOPPING SYSTEM

Seu servidor deverá estar com a versão 3.24 ou superior do Mikrotik RouterOS e no mínimo 4 (quatro) placas de rede.

How To Design An Eprescription System

PHP Framework Performance for Web Development Between Codeigniter and CakePHP

JDBC (Java / SQL Programming) CS 377: Database Systems

Real SQL Programming 1

apache.org. ApacheCon NA - Vancouver BC November :30p. husted@apache.org

HTML Form Widgets. Review: HTML Forms. Review: CGI Programs

CS2506 Operating Systems II Lab 8, 8 th Tue/03 /2011 Java API

Transcription:

Aplicação ASP.NET MVC 4 Usando Banco de Dados Neste exemplo simples, vamos desenvolver uma aplicação ASP.NET MVC para acessar o banco de dados Northwind, que está armazenado no servidor SQL Server e, listar todas as categorias. Para tal, temos que executar as seguintes tarefas: 1. Verificar se o banco de dados Northwind existe no servidor SQL Server. 2. Caso não exista, temos que cria-lo. Para isso, execute o script que está no meu site. 3. Verifique os campos da tabela Categorie. 4. Crie os Procedimentos no banco de dados Northwind Stored procedures no Northwind USE NORTHWIND GO CREATE PROCEDURE [dbo].[stpinserircategory] @CategoryName varchar(15), @Description Text AS Insert Into Categories (CategoryName, Description) Values (@CategoryName, @Description) CREATE PROCEDURE stpeditarcategory @CategoryID int, @CategoryName varchar(15), @Description Text AS UPDATE Categories Set CategoryName = @CategoryName, Description = @Description WHERE CategoryID = @CategoryID GO CREATE PROCEDURE stpdeletarcategory @CategoryID int AS DELETE FROM Categories WHERE CategoryID = @CategoryID GO 5. Crie uma aplicação ASP.NET MVC 4. 6. Crie o modelona pasta Models, de acordo com o código a seguir: Modelo em C# using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Web; using System.Web.Configuration; namespace MvcComDB.Models

public class CategoryRepository Criar uma lista de categorias public List<Category> GetAllCategories() ConnectionStringSettings getstring = WebConfigurationManager.ConnectionStrings["nwind"] as ConnectionStringSettings; if (getstring!= null) string ssql = "select CategoryID, CategoryName, Description from Categories"; using (SqlConnection con = new SqlConnection(getString.ConnectionString)) List<Category> lst = new List<Category>(); SqlDataReader r = null; SqlCommand cmd = new SqlCommand(sSQL, con); con.open(); r = cmd.executereader(commandbehavior.closeconnection); while (r.read()) Category category = new Category(); category.categoryid = Convert.ToInt16(r["CategoryID"]); category.categoryname = r["categoryname"].tostring(); category.description = r["description"].tostring(); lst.add(category); return lst; return null; public Category GetCategory(int id) ConnectionStringSettings getstring = WebConfigurationManager.ConnectionStrings["nwind"] as ConnectionStringSettings; if (getstring!= null) String ssql1 = "select CategoryID, CategoryName, Description from Categories "; String ssql2 = "WHERE CategoryID = " + id.tostring(); String ssql = ssql1 + ssql2; using (SqlConnection con = new SqlConnection(getString.ConnectionString)) SqlDataReader r = null; SqlCommand cmd = new SqlCommand(sSQL, con); con.open(); Category category = new Category(); r = cmd.executereader(commandbehavior.closeconnection); while (r.read()) category.categoryid = Convert.ToInt16(r["CategoryID"]); category.categoryname = r["categoryname"].tostring(); category.description = r["description"].tostring(); return category;

return null; public void InserirCategory(Category category) ConnectionStringSettings getstring = WebConfigurationManager.ConnectionStrings["nwind"] as ConnectionStringSettings; if (getstring!= null) using (SqlConnection con = new SqlConnection(getString.ConnectionString)) SqlCommand cmd = new SqlCommand("stpInserirCategory",con); cmd.commandtype = CommandType.StoredProcedure; cmd.parameters.addwithvalue("@categoryname", category.categoryname); cmd.parameters.addwithvalue("@description", category.description); con.open(); cmd.executenonquery(); catch (SqlException ex) throw new Exception("Erro: " + ex.message); finally con.close(); public void EditCategory(Category category) ConnectionStringSettings getstring = WebConfigurationManager.ConnectionStrings["nwind"] as ConnectionStringSettings; if (getstring!= null) using (SqlConnection con = new SqlConnection(getString.ConnectionString)) SqlCommand cmd = new SqlCommand("stpEditarCategory", con); cmd.commandtype = CommandType.StoredProcedure; cmd.parameters.addwithvalue("@categoryid", category.categoryid); cmd.parameters.addwithvalue("@categoryname", category.categoryname); cmd.parameters.addwithvalue("@description", category.description); con.open(); cmd.executenonquery(); catch (SqlException ex) throw new Exception("Erro: " + ex.message); finally con.close();

public void DeleteCategory(int id) ConnectionStringSettings getstring = WebConfigurationManager.ConnectionStrings["nwind"] as ConnectionStringSettings; if (getstring!= null) using (SqlConnection con = new SqlConnection(getString.ConnectionString)) SqlCommand cmd = new SqlCommand("stpDeletarCategory", con); cmd.commandtype = CommandType.StoredProcedure; cmd.parameters.addwithvalue("@categoryid", id); con.open(); cmd.executenonquery(); catch (SqlException ex) throw new Exception("Erro: " + ex.message); finally con.close(); public class Category public int CategoryID get; set; public string CategoryName get; set; public string Description get; set; 7. No arquivo web.config, acrescente a linha de código a seguir: <add name="nwind" connectionstring="data Source=(Local);Initial Catalog=Northwind; Integrated Security=true;"/> 8. Crie o controle, na pasta Controllers, de acordo com o código a seguir: Controle em C# using MvcComDB.Models; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace MvcComDB.Controllers

public class CategoryController : Controller GET: /Category/ public ActionResult Index() var model = _db.getallcategories(); return View(model); GET: /Category/Details/5 CategoryRepository _db = new CategoryRepository(); public ActionResult Details(int id) var model = _db.getcategory(id); return View(model); GET: /Category/Create public ActionResult Create() return View(); POST: /Category/Create [HttpPost] public ActionResult Create(MvcComDB.Models.CategoryRepository.Category category, FormCollection collection) if (!ModelState.IsValid) return View(); _db.inserircategory(category); return RedirectToAction("Index"); catch return View(); GET: /Category/Edit/5 public ActionResult Edit(int id) var model = _db.getcategory(id);

return View(model); POST: /Category/Edit/5 [HttpPost] public ActionResult Edit(CategoryRepository.Category category, FormCollection collection) if (!ModelState.IsValid) return View(); _db.editcategory(category); return RedirectToAction("Index"); catch return View(); GET: /Category/Delete/5 public ActionResult Delete(int id) var model = _db.getcategory(id); return View(model); POST: /Category/Delete/5 [HttpPost] public ActionResult Delete(int id, FormCollection collection) TODO: Add delete logic here if (!ModelState.IsValid) return View(); _db.deletecategory(id); return RedirectToAction("Index"); catch return View(); 9. Crie as Views

Views Index @model IEnumerable<MvcComDB.Models.CategoryRepository.Category> @ ViewBag.Title = "Index"; <h2>index</h2> <p> @Html.ActionLink("Create New", "Create") </p> <table> <tr> <th> @Html.DisplayNameFor(model => model.categoryid) </th> <th> @Html.DisplayNameFor(model => model.categoryname) </th> <th> @Html.DisplayNameFor(model => model.description) </th> <th></th> </tr> @foreach (var item in Model) <tr> <td> @Html.DisplayFor(modelItem => item.categoryid) </td> <td> @Html.DisplayFor(modelItem => item.categoryname) </td> <td> @Html.DisplayFor(modelItem => item.description) </td> <td> @Html.ActionLink("Edit", "Edit", new id=item.categoryid ) @Html.ActionLink("Details", "Details", new id=item.categoryid ) @Html.ActionLink("Delete", "Delete", new id=item.categoryid ) </td> </tr> </table> View Create @model MvcComDB.Models.CategoryRepository.Category @ ViewBag.Title = "Create"; <h2>create</h2> @using (Html.BeginForm())

@Html.ValidationSummary(true) <fieldset> <legend>category</legend> <div class="editor-label"> @Html.LabelFor(model => model.categoryid) <div class="editor-field"> @Html.EditorFor(model => model.categoryid) @Html.ValidationMessageFor(model => model.categoryid) <div class="editor-label"> @Html.LabelFor(model => model.categoryname) <div class="editor-field"> @Html.EditorFor(model => model.categoryname) @Html.ValidationMessageFor(model => model.categoryname) <div class="editor-label"> @Html.LabelFor(model => model.description) <div class="editor-field"> @Html.EditorFor(model => model.description) @Html.ValidationMessageFor(model => model.description) <p> <input type="submit" value="create" /> </p> </fieldset> <div> @Html.ActionLink("Back to List", "Index") @section Scripts @Scripts.Render("~/bundles/jqueryval") View Edit @model MvcComDB.Models.CategoryRepository.Category @ ViewBag.Title = "Edit"; <h2>edit</h2> @using (Html.BeginForm()) @Html.ValidationSummary(true) <fieldset> <legend>category</legend> @Html.HiddenFor(model => model.categoryid) <div class="editor-label">

@Html.LabelFor(model => model.categoryname) <div class="editor-field"> @Html.EditorFor(model => model.categoryname) @Html.ValidationMessageFor(model => model.categoryname) <div class="editor-label"> @Html.LabelFor(model => model.description) <div class="editor-field"> @Html.EditorFor(model => model.description) @Html.ValidationMessageFor(model => model.description) <p> <input type="submit" value="save" /> </p> </fieldset> <div> @Html.ActionLink("Back to List", "Index") @section Scripts @Scripts.Render("~/bundles/jqueryval") View Detalhes @model MvcComDB.Models.CategoryRepository.Category @ ViewBag.Title = "Details"; <h2>details</h2> <fieldset> <legend>category</legend> <div class="display-label"> @Html.DisplayNameFor(model => model.categoryname) <div class="display-field"> @Html.DisplayFor(model => model.categoryname) <div class="display-label"> @Html.DisplayNameFor(model => model.description) <div class="display-field"> @Html.DisplayFor(model => model.description) </fieldset> <p> @Html.ActionLink("Edit", "Edit", new id=model.categoryid ) @Html.ActionLink("Back to List", "Index")

</p> View Delete @model MvcComDB.Models.CategoryRepository.Category @ ViewBag.Title = "Delete"; <h2>delete</h2> <h3>are you sure you want to delete this?</h3> <fieldset> <legend>category</legend> <div class="display-label"> @Html.DisplayNameFor(model => model.categoryname) <div class="display-field"> @Html.DisplayFor(model => model.categoryname) <div class="display-label"> @Html.DisplayNameFor(model => model.description) <div class="display-field"> @Html.DisplayFor(model => model.description) </fieldset> @using (Html.BeginForm()) <p> <input type="submit" value="delete" /> @Html.ActionLink("Back to List", "Index") </p> 10. No arquivo web.config, acrescente a seguinte linha de código Web.config <connectionstrings> <add name="nwind" connectionstring="data Source=(Local);Initial Catalog=Northwind;Integrated Security=true;"/> </connectionstrings>