Skip to main content

Sample MVC database access example source code

step 1-> Create a databse as follows








Step 2-> Write stored Procedure for Insertion

USE [Guestbook]
GO
/****** Object:  StoredProcedure [dbo].[spInsert]    Script Date: 07/14/2014 14:29:50 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER PROCEDURE [dbo].[spInsert](@Name nvarchar(50),@Message nvarchar(50),@DateAdded datetime)

AS
BEGIN
    Insert into GuestBookEntry(Name,Message,DateAdded) values(@Name,@Message,@DateAdded)
END






step-> Create Model as



using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;
using System.Globalization;
using System.Web.Mvc;
using System.Data.Sql;
using System.Configuration;
using System.Web.Security;
using System.Data.SqlClient;
using System.Data;
namespace GuestBook.Models
{
    //public class GuestBookContext : DbContext
    //{
    //    public GuestBookContext()
    //        : base("dbConnection")
    //    {
    //    }

    //    public DbSet<GuestBookEntry> Entries { get; set; }
    //}
    //[Table("GuestBookEntry")]
    public class GuestBookEntry
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Message { get; set; }
        public DateTime DateAdded { get; set; }
    }
    public class dataAccesLayer
    {
        public string insertData(GuestBookEntry gbe)
        {
            SqlConnection con = null;

            string result = "";

            try
            {

                con = new SqlConnection(ConfigurationManager.ConnectionStrings["dbConnection"].ConnectionString);

                SqlCommand cmd = new SqlCommand("spInsert", con);

                cmd.CommandType = CommandType.StoredProcedure;

                cmd.Parameters.AddWithValue("@Name", gbe.Name);

                cmd.Parameters.AddWithValue("@Message", gbe.Message);

                cmd.Parameters.AddWithValue("@DateAdded",gbe.DateAdded);
                       

                con.Open();

                result = cmd.ExecuteScalar().ToString();

                return result;

            }

            catch
            {

                return result = "";

            }

            finally
            {

                con.Close();

            }
        }

    }
}



step 4->Create a Controller 


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using GuestBook.Models;

namespace GuestBook.Controllers
{
    public class GuestBookController : Controller
    {
        //
        // GET: /GuestBook/
     
           
        public ActionResult Ceate()
        {
            return View();
        }
        [HttpPost]
        public ActionResult Ceate(GuestBookEntry entry)
        {
            entry.DateAdded = DateTime.Now;
           
            dataAccesLayer dal = new dataAccesLayer();
            dal.insertData(entry);
            return Content("successfully added");
        }

    }
}




step 5-> Create a View as 


@model GuestBook.Models.GuestBookEntry
@{
   
    ViewBag.Title = "Add New entry";
}

<h2>AddNew Entry</h2>
@using (Html.BeginForm())

{

    <table width="100%">    

        <tr>

            <td>

                @Html.LabelFor(a => a.Name)

            </td>

        </tr>

        <tr>

            <td>

                @Html.TextBoxFor(a => a.Name)

              

            </td>

        </tr>

        <tr>

            <td>

                @Html.LabelFor(a => a.Message)

            </td>

        </tr>

        <tr>

            <td>

                @Html.TextBoxFor(a => a.Message)

            

            </td>

        </tr>


        <tr>

            <td colspan="2">

                <input id="Submit1" type="submit" value="submit" />

            </td>

        </tr>

    </table>  

}




Comments

Popular posts from this blog

NHibernate Introduction

 NHibernate NHibernate is an open source Object-Relational Mapping (ORM) tool for the .Net platform… and the existing documentation and tutorials that I could find, whilst plentiful, are not aimed at those new to or inexperienced with ORM. This tutorial is based on using Visual Studio (I used 2008 beta 2) and Sql Server, however the database used is almost immaterial (one of the advantages of using an OR mapper). If you already know what NHibernate and ORM are and you want to use it but just need to know how?  Otherwise, read on. WTF is ORM? There is plenty of good stuff out there on what Object-Relational Mapping is, try wikipedia or the intro here (the tutorial is a bit out of date but the explanation is good) or there’s always Google . However, in a nutshell, ORM is the process of mapping business objects (think OOP) to database relations (read tables). An OR Mapper is a tool that manages this process. There are several different OR Mappers available for ...

Computer Science Defenition

Computer Science Computer science is the scientific and practical approach to computation and its applications. It is the systematic study of the feasibility, structure, expression, and mechanization of the methodical procedures (or algorithms ) that underlie the acquisition, representation, processing, storage, communication of, and access to information , whether such information is encoded as bits in a computer memory or transcribed in genes and protein structures in a biological cell . [1] A computer scientist specializes in the theory of computation and the design of computational system

Understanding machine learning

What is machine learning does?  It Finds patterns in data and uses those patterns to predict the future.          EXAMPLES :  Detecting credit card fraud : You can use machine learning  detect credit card fraud, Suppose you have data about previous credit card transactions. You could find patterns in that data potentially  that allows you to detect when a new credit card transaction is likely to be fraudulent. Determining whether a customer is likely to switch to a competitor :  You could possibly find the patterns in the existing customer data that will help you do that Lots more What does it mean to learn ? Yes it's something like your own learning process. You have learned reading,listening, walking everything by using your experience on it, the data you have in your mind and continuous improvements.  How did you learn to read? Well learning requires identifying patterns. Reading for instance you ...