Introduction:
Here I will explain how to insert data into database in asp.net mvc with example or asp.net mvc insert and get data from database using ADO.NET with example or asp.net mvc get data from database with example. By using ADO.NET we can easily insert data and get data from database in asp.net mvc based on our requirements.
Description:
In previous articles I explained asp.net mvc upload files to server or folder with example, asp.net mvc sample application project with source code, asp.net mvc cross site request forgery attacks (csrf) with example, asp.net mvc global action filters with example, razor view engine in asp.net mvc with example, asynchronous controllers in asp.net mvc with example, difference between viewbag, viewdata and tempdata with example, validation using fluent validation in asp.net mvc and many articles relating to asp.net mvc, asp.net, c#,vb.net. Now I will explain how to insert data into database and get data from database in asp.net mvc with example.
In previous articles I explained asp.net mvc upload files to server or folder with example, asp.net mvc sample application project with source code, asp.net mvc cross site request forgery attacks (csrf) with example, asp.net mvc global action filters with example, razor view engine in asp.net mvc with example, asynchronous controllers in asp.net mvc with example, difference between viewbag, viewdata and tempdata with example, validation using fluent validation in asp.net mvc and many articles relating to asp.net mvc, asp.net, c#,vb.net. Now I will explain how to insert data into database and get data from database in asp.net mvc with example.
Before
we proceed to insert or get data from database first design userdetails table like as shown below.
Column
Name
|
Data
Type
|
Allow
Nulls
|
userid
|
Int(IDENTITY=TRUE)
|
NO
|
username
|
varchar(50)
|
Yes
|
education
|
Varchar(50)
|
Yes
|
location
|
Varchar(50)
|
Yes
|
Or
use following query to create userdetails
table in database.
create table userdetails(
userid int primary key identity,
username varchar(50),
education varchar(50),
location varchar(50)
)
|
To
insert and get data from userdetails write query like as shown below
Create Procedure usercrudoperations
(
@name varchar(50),
@education varchar(50),
@location varchar(50),
@status varchar(10)
)
As
BEGIN
-- Insert User
Details
if @status ='INSERT'
BEGIN
INSERT INTO userdetails(username,education,location)
VALUES(@name,@education,@location)
END
-- Get User Details
if @status ='GET'
BEGIN
SELECT * FROM userdetails
END
END
|
Once
we create userdetails table and
stored procedure to insert and get data from database now create asp.net mvc application for
that Open visual studio --> Go to
File --> Select New --> Project like as shown below
Once
we select Project new popup will open in that select Asp.Net Web Application
and give name to application and click OK like as shown below
Once
we finished creating application our project structure will be like as shown
below
Now
we will add new model to our
application to define properties in our application for that right click on Models folder --> select Add -->
select Class like as shown below
Once
we click on Class new popup will open in that give name of your model as “UserDetails”
and click Add button like as shown below
Now
open newly created model (UserDetails) and write the code like as
shown below
using System.Collections.Generic;
namespace InsertGetUserDetails.Models
{
public class UserDetails
{
public int UserId { get; set; }
public string UserName { get; set; }
public string Education { get; set; }
public string Location { get; set; }
public List<UserDetails> usersinfo { get; set; }
}
}
|
Now we will add new
controller to insert or get data from database for that right click on
Controller folder --> select Add
--> Controller like as shown
below
Once we click on Controller
new popup will open in that select MVC 5
Controller – Empty and click Add
like as shown below.
Once click on Add new
window will open in that enter the name of controller and click Add like as shown
below
Now open newly created
controller and write the code like as shown below
using System;
using System.Collections.Generic;
using System.Web.Mvc;
using InsertGetUserDetails.Models;
using System.Data.SqlClient;
using System.Data;
namespace InsertGetUserDetails.Controllers
{
public class UserController : Controller
{
// GET: User
public ActionResult
InsertUserDetails()
{
UserDetails objuser = new UserDetails();
DataSet ds = new DataSet();
using (SqlConnection con = new SqlConnection("Data Source=Suresh;Integrated
Security=true;Initial Catalog=MySamplesDB"))
{
using (SqlCommand cmd = new SqlCommand("usercrudoperations", con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@status", "GET");
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
List<UserDetails> userlist = new List<UserDetails>();
for (int i = 0; i <
ds.Tables[0].Rows.Count; i++)
{
UserDetails uobj = new UserDetails();
uobj.UserId = Convert.ToInt32(ds.Tables[0].Rows[i]["userid"].ToString());
uobj.UserName =
ds.Tables[0].Rows[i]["username"].ToString();
uobj.Education =
ds.Tables[0].Rows[i]["education"].ToString();
uobj.Location =
ds.Tables[0].Rows[i]["location"].ToString();
userlist.Add(uobj);
}
objuser.usersinfo =
userlist;
}
con.Close();
}
return View(objuser);
}
[HttpPost]
public ActionResult InsertUserDetails(UserDetails user)
{
UserDetails objuser = new UserDetails();
using (SqlConnection con = new SqlConnection("Data Source=Suresh;Integrated
Security=true;Initial Catalog=MySamplesDB"))
{
using (SqlCommand cmd = new SqlCommand("usercrudoperations", con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@name", user.UserName);
cmd.Parameters.AddWithValue("@education", user.Education);
cmd.Parameters.AddWithValue("@location", user.Location);
cmd.Parameters.AddWithValue("@status", "INSERT");
con.Open();
ViewData["result"] = cmd.ExecuteNonQuery();
con.Close();
}
}
return View();
}
}
}
|
If you observe above
controller code, we defined InsertUserDetails
method two times one is for insertion and another for getting data from
database.
Now we will add view to our
controller action method for that right click on InsertUserDetails action method --> select Add View like as shown below
Now give name “InsertUserDetails” to view, select
template as “Empty” and select Model
class as “UserDetails” which we
created in our application then click on Add button like as shown below.
The newly created view will
be added under Views folder like as
shown below
Now open newly created view
and write the code like as shown below
@model InsertGetUserDetails.Models.UserDetails
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>InsertUserDetails</title>
<script src="~/Scripts/jquery-1.10.2.js"></script>
</head>
<body>
@using (Html.BeginForm("InsertUserDetails","User",FormMethod.Post)) {
<table>
<tr>
<td>User Name:</td>
<td>@Html.TextBoxFor(u=>u.UserName)</td>
</tr>
<tr>
<td>Education:</td>
<td>@Html.TextBoxFor(u
=> u.Education)</td>
</tr>
<tr>
<td>Location:</td>
<td>@Html.TextBoxFor(u=>u.Location)</td>
</tr>
<tr>
<td></td>
<td> <input type="submit" value="Register" /> </td>
</tr>
</table>
}
<h4>User Details</h4>
@if (Model != null)
{
if (Model.usersinfo.Count > 0)
{
<table>
<tr>
<th>UserId</th>
<th>UserName</th>
<th>Education</th>
<th>Location</th>
</tr>
@foreach (var item in Model.usersinfo)
{
<tr>
<td>@Html.DisplayFor(modelitem
=> item.UserId) </td>
<td>@Html.DisplayFor(modelitem
=> item.UserName)</td>
<td>@Html.DisplayFor(modelitem
=> item.Education)</td>
<td>@Html.DisplayFor(modelitem
=> item.Location)</td>
</tr>
}
</table>
}
else {
<b>No Details Found.</b>
}
}
<script type="text/javascript">
$(function () {
var msg = '@ViewData["result"]';
if (msg == '1')
{
alert("User Details Inserted Successfully");
window.location.href
= "@Url.Action("InsertUserDetails", "User")";
}
});
</script>
</body>
</html>
|
Now we will run and see the
application result. (url always in the format of http://localhost:portnumber/controller name/action method name) and
check the output that would be like as shown below
If you enjoyed this post, please support the blog below. It's FREE! Get the latest Asp.net, C#.net, VB.NET, jQuery, Plugins & Code Snippets for FREE by subscribing to our Facebook, Twitter, RSS feed, or by email. |
|||
|
|||
2 comments :
Its not working......When I was executing the programme, it shows "Procedure or function 'usercrudoperations' expects parameter '@uname', which was not supplied."
actually it does not work beacause the stored procedure has not default values for the variables when you send the "GET" status, if you modify the SP to have default values it does work.
Note: Only a member of this blog may post a comment.