Insert Details into Database using MVC



Introduction :
  Hi, In this tutorial you will look how to insert the data into database. using MVC. you can follow the below steps for this tutorial

Step 1 : Select  MVC  web application


Step 2 : Select Empty template with Razor view Engine.


Step 3 : Create the Database,Table for Which you are going to insert


Step 4 : Right Click on model folder add a class file to it.




Step 5 : Give the name to the class file created in Model folder. 


Step 6 : Start writing code to model.
  1. Create Property class for the details to insert.
  2. Create function for inserting details( DB Layer Coding )
Your model coding looks as below.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.Data;
using System.Data.SqlClient;

namespace MVC_1_InsertData.Models
{
public class RegistrationDetails
{

//creatinng property class for the details to insert
public string Name { get; set; }
public string EmailID { get; set; }
public string Mobilenumber { get; set; }
public string Address { get; set; }

SqlConnection con = new SqlConnection("Your connection string");
SqlCommand cmd = new SqlCommand();

//Creating function to insert details
public string InsertRegDetails(RegistrationDetails obj)
{
cmd.CommandText = "Insert into [Table] values('" + obj.Name + "','" + obj.EmailID + "'," + Convert.ToInt64(obj.Mobilenumber) + ",'" + obj.Address + "')";
cmd.Connection = con;
try
{
con.Open();
cmd.ExecuteNonQuery();
con.Close();
return "Success";
}
catch (Exception es)
{
    throw es;
}
}
}
}

Step 7 : Right Click on Controller folder and create new Controller.


Step 8: Give name to the controller followed by the text 'Controller'


Step 9 : Your basic controller Structure 


Step 9 : Write coding to your Controller

Your controller code looks as below

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

namespace MVC_1_InsertData.Controllers
{
 public class RegController : Controller
  {
   // Calling when we first hit controller.
     public ActionResult InsertDetails()
       {
        return View();
       }
   // Calling on http post (on Submit)
     [HttpPost]
     public ActionResult InsertDetails(RegistrationDetails obj)
      {
       RegistrationDetails objreg = new RegistrationDetails();
       string result = objreg.InsertRegDetails(obj);
       ViewData["result"] = result;
       ModelState.Clear();
      return View();
     }
  }
}

Step 10 : Create view by placing your cursor near your ActionResult name as below.


Step 11 : Keep View name as it looks.  check strongly typed view select your model.


Step 12 : Your View Firstly looks like below.



Step 13 : Add the below code to the view.

@model MVC_1_InsertData.Models.RegistrationDetails

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>InsertDetails</title>
</head>
<body>
    <div>
@using (Html.BeginForm())
{
    <table>
        <tr>
        <td>Name</td>
        <td>@Html.TextBoxFor(x => x.Name)</td>
        </tr>
        <tr>
        <td>Email ID</td>
        <td>@Html.TextBoxFor(x => x.EmailID)</td>
        </tr>
        <tr>
        <td>Mobile Number</td>
        <td>@Html.TextBoxFor(x => x.Mobilenumber)</td>
        </tr>
        <tr>
        <td>Address</td>
        <td>@Html.TextAreaFor(x => x.Address)</td>
        </tr>
        <tr>
        <td></td>
        <td><input id="Submit" type="submit" value="submit" /></td>
        </tr>
        </table>
    }
        @{
            if (ViewData["result"] != "" && ViewData["result"] != null)
            {
                ViewData["result"] = null;
                <script type="text/javascript" language="javascript">
                    alert("Details saved Successfully");
                </script>
            }
        }

    </div>
</body>
</html>

Your Coding part is completed. Now Run your Application,you will find an error that 'resource Cannot be find' Now Change your URL As 'http://localhost:60622/Reg/InsertDetails' to get Output.

To avoid this doing manually later tutorials you will see Routing concepts.