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 QueryOver Class And Projection....

Introduction The ICriteria API is NHibernate's implementation of Query Object . NHibernate 3.0 introduces the QueryOver api, which combines the use of Extension Methods and Lambda Expressions (both new in .Net 3.5) to provide a statically typesafe wrapper round the ICriteria API. QueryOver uses Lambda Expressions to provide some extra syntax to remove the 'magic strings' from your ICriteria queries. So, for example: .Add(Expression.Eq("Name", "Smith")) becomes: .Where<Person>(p => p.Name == "Smith") With this kind of syntax there are no 'magic strings', and refactoring tools like 'Find All References', and 'Refactor->Rename' work perfectly. Note: QueryOver is intended to remove the references to 'magic strings' from the ICriteria API while maintaining it's opaqueness. It is not a LINQ provider; NHibernate 3.0 has a built-in ...

Passing Data from View to Controller Using Ajax Example Jquery

Jquery       $ ( '#btnSaveComments' ). click ( function () { var comments = $ ( '#txtComments' ). val (); var selectedId = $ ( '#hdnSelectedId' ). val (); $ . ajax ({ url : '<%: Url.Action("SaveComments")%>' , data : { 'id' : selectedId , 'comments' : comments }, type : "post" , cache : false , success : function ( savingStatus ) { $ ( "#hdnOrigComments" ). val ( $ ( '#txtComments' ). val ()); $ ( '#lblCommentsNotification' ). text ( savingStatus ); }, error : function ( xhr , ajaxOptions , thrownError ) { $ ( '#lblCommentsNotification' ). text ( "Error encountered while saving the comments." ); } }); });     Controller    [ HttpPost ] public ActionResult SaveComments ( int id , string com...

The Core Concepts of Angular -- Jithin CJ

I started to learn angular from 2016, I was very curious about the celibacy of this super hero. From my initial understanding is like, the power of angular is only limited on " html decoration "  But this JavaScript framework has the potential to re-define conventional html-css patterns . Modern browsers support for things like modules, classes, lambdas, generators, etc. These features fundamentally transform the JavaScript programming experience. But big changes aren't constrained merely to JavaScript. Web Components are on the horizon. The term Web Components usually refers to a collection of four related W3C specifications: Custom Elements - Enables the extension of HTML through custom tags.  HTML Imports - Enables packaging of various resources (HTML, CSS, JS, etc.).  Template Element - Enables the inclusion of inert HTML in a document.  Shadow DOM - Enables encapsulation of DOM and CSS.  Developers can create fully encapsulated (Shadow D...