Wednesday, 13 June 2018

Insert Data into DataBase using ASP.NET MVC with ADO.NET

Step 1: Create database (CRUDDEMO) in Microsoft Sql Server Management Studio
Step 2: Create table CRUDPERSON (Id, Name, and Country)
Set primary key as Id and Set Is identity property yes
Step 3:

Step 4: Create a project and choose empty template from mvc application (CRUD1)
Step 5: Create a model-> Go to Model-> Right Click on Model->add class (CST.cs)
Step 6: Add following code in CST.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace CRUD1.Models
{
    public class CST
    {
        public int Id { get; set; }

        ///<summary>
        /// Gets or sets Name.
        ///</summary>
        public string Name { get; set; }

        ///<summary>
        /// Gets or sets Country.
        ///</summary>
        public string Country { get; set; }
    }
}
Step 7:Set connectionString in Web.config

<configuration>
<connectionStrings>
   <add name="ConnString" connectionString="Server=.\SQLExpress; Initial Catalog=CRUDDEMO; Integrated Security=True;" providerName="System.Data.SqlClient" />
  </connectionStrings>
</configuration>
Step 8: Create Empty controller(Home) and  add following namespace
using System.Configuration;
using System.Data.SqlClient;
using CRUD1.Models;


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Configuration;
using System.Data.SqlClient;
using CRUD1.Models;
namespace CRUD1.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/

        public ActionResult Index()
        {
            return View();
        }
        [HttpPost]
        public ActionResult Index(CST customer)
        {
            string constr = ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString;
             //SqlConnection conn = new SqlConnection(@"Data Source=COMP1\\SQLEXPRESS;Initial Catalog=ERPFinalEntities1;Integrated Security=true");
       
            using (SqlConnection con = new SqlConnection(constr))
            {
                string query = "INSERT INTO CRUDPERSON(Name, Country) VALUES(@Name, @Country)";
                query += " SELECT SCOPE_IDENTITY()";
                using (SqlCommand cmd = new SqlCommand(query))
                {
                    cmd.Connection = con;
                    con.Open();
                    cmd.Parameters.AddWithValue("@Name", customer.Name);
                    cmd.Parameters.AddWithValue("@Country", customer.Country);
                    customer.Id = Convert.ToInt32(cmd.ExecuteScalar());
                    con.Close();
                }
            }

            return View(customer);
        }
    }
}

Step 9: Create  View(Index.cshtml) And add following code





@model CRUD1.Models.CST

@{
    ViewBag.Title = "Index";
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width"/>
    <title>Index</title>
    <style type="text/css">
        body {
            font-family: Arial;
            font-size: 10pt;
        }

        table {
            border: 1px solid #ccc;
            border-collapse: collapse;
            background-color: #fff;
        }

        table th {
            background-color: red;
            color: #333;
            font-weight: bold;
        }

        table th, table td {
            padding: 5px;
            border: 1px solid #ccc;
        }

        table, table table td {
            border: 0px solid #ccc;
        }

        input[type=text], select {
            width: 150px;
        }
    </style>
</head>
<body>
    @using (Html.BeginForm("Index", "Home", FormMethod.Post))
    {
        <table cellpadding="0" cellspacing="0">
            <tr>
                <th colspan="2" align="center">Customer Details</th>
            </tr>
            <tr>
                <td>Name: </td>
                <td>
                    @Html.TextBoxFor(m => m.Name)
                </td>
            </tr>
            <tr>
                <td>Country: </td>
                <td>
                   @Html.DropDownListFor(m => m.Country, new List<SelectListItem>
                   { new SelectListItem{Text="India", Value="India"},
                     new SelectListItem{Text="China", Value="China"},
                     new SelectListItem{Text="Australia", Value="Australia"},
                     new SelectListItem{Text="France", Value="France"},
                     new SelectListItem{Text="Unites States", Value="Unites States"},
                     new SelectListItem{Text="Russia", Value="Russia"},
                     new SelectListItem{Text="Canada", Value="Canada"}},
                     "Please select")
                </td>
            </tr>
            <tr>
                <td></td>
                <td><input type="submit" value="Submit"/></td>
            </tr>
        </table>
    }

    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    @if (Model != null)
    {
        <script type="text/javascript">
            $(function () {
                alert("Inserted Data successully");
            });
        </script>
    }
</body>
</html>
Step 10: Set Controller and action name in RouteConfig.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

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

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


1 comment:

  1. Python is an open-source, high level, interpreted programming language which offers great opportunities for object-oriented programming. Choosing a python training program from Red Prism Group, which is best training institute for python in noida.

    ReplyDelete

apply function in R

1) apply function: It takes 3 arguments matrix,margin and function.. Example: m<-matrix(c(1,2,3,4),nrow=2,ncol=2) m #1 indicates it is ap...