Thumb

How To Insert Data Into Database Using Stored Procedure In C# | Asp.Net mvc


11/7/2019 7:35:46 AM

Download Project  (Full Project)

Step 1:

In this tutorial I will show how to insert Data into Database Using Stored Procedure in Asp.Net MVC. First create asp.net MVC web application in the home controller create a method name as “Save”. This save method takes a parameter and Execute the query with help of Stored procedure. This procedure responsible to take a parameter name as “@name” and   Execute the query. When query is Execute data save in the table. Given bellow the controller code:

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace HighChart.Controllers
{
    public class StoredProcedureController : Controller
    {
        // GET: StoredProcedure
        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public void Save(string gender)
        {

            SqlConnection con = new SqlConnection("Data Source=DESKTOP-LE3GNR4;Initial Catalog=crud;Integrated Security=True");
            SqlCommand cmd = con.CreateCommand();
            cmd.CommandText = "Execute SaveName @name";
            cmd.Parameters.Add("@name",SqlDbType.VarChar,50).Value= gender;
            con.Open();
            cmd.ExecuteNonQuery();
            con.Close();
        }

    }
}

Step 2:

Now in the controller index view just represent the some HTML tag for post the data into controller. This form tag post method responsible to post text box value by the name field. This name files string value so controller takes the string type value. This form tag “action” sends to data into method. Now given bellow the view code:

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

<form action="~/StoredProcedure/Save" method="post">
    <input type="text" name="gender" value="" />
    <input type="submit" name="" value="Insert" />
</form>

Step 3:

Now build and run the project.

About Teacher

Reza Karim

Software Engineer

More about him