CRUD are the basic functions of persistent storage.It is also used for inserting, viewing data , searching and changing information.
mainly computer based forms and reports. The term was firstly used by James Martin in 1983.
Operation SQL HTTP DDS
Create INSERT PUT / POST write
Read (Retrieve) SELECT GET read / take
Update (Modify) UPDATE PUT / PATCH write
Delete (Destroy) DELETE DELETE dispose
In this blog I have discussed about the CRUD operation in MVC-4.Below are Steps to open an MVC Application in .net Framework
Open .net Framework click on FILE on top left, a window popup will arise.
Inside Templates click on Visual C#=>Web=>Asp.net MVC 4 WEB Application=> cilck ok=>click ok (internet application).
All the Classes and Entites will be inside Models(ex Student,Courses etc).
Views will contain all front end part like Html.
Controller will get request from views and save it into the database
Now Lets get started.
Right click on Models =>Add =>class =>name it and Add.
public class Student
{
public Student()
{
City = new Cities();
}
private string name;
private string picture;
private Cities city;
public string Name
{
get
{
return name;
}
set
{
name= value;
}
}
public string Picture
{
get
{
return picture;
}
set
{
picture= value;
}
}
public Cities City
{
get
{
return city;
}
set
{
city= value;
}
}
}
public class Cities
{
public Cities()
{
}
public Cities(int id, string name)
{
this.CityId = id;
this.CityName = name;
}
public int CityId { get; set; }
public string CityName { get; set; }
}
Now Move to the controller and right click on it, => Add Controller => name it, select basic Read/wrie operations and click Add.
Some functions will be built automatically. these methods are called actions which are invoked after request from view.
Now go to Action Create.
public ActionResult Create()
{
List cities = new List();
cities.Add(new Cities(1, "delhi"));
cities.Add(new Cities(2, "mumbai"));
cities.Add(new Cities(3, "chennai"));
cities.Add(new Cities(4, "kolkata"));
cities.Add(new Cities(5, "kohima"));
cities.Add(new Cities(6, "dehradun"));
ViewBag.cities = new SelectList(cities.ToArray(), "CityId", "CityName");
return View();
}
public ActionResult Create(FormCollection collection)
{
return View();
}
Right click inside create function => Add view => name it ,select view engine(rajor)=> tightly bind with Model=> Add.
A view will be created in Views folder with controller name.
Now your view page must contain a TextBox , File dialog for image and dropdown list for city. So make the following changes as given below . For dropdownlist multiple values are required with their name and id, in above example i have provided values hardcoded , but list can be used fetching from database.
@using (Html.BeginForm("Create", "Student", FormMethod.Post, new { enctype = "multipart/form-data" }))
Your Create view page must look like this.
@model MvcApplication2.Models.Student
@{
ViewBag.Title = "Create";
}
<h2>Create</h2>
@using (Html.BeginForm("Create", "Student", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<fieldset>
<legend>Student</legend>
<div class="editor-label">
@Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Name)
@Html.ValidationMessageFor(model => model.Name)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Picture)
</div>
<div class="editor-field">
<input type="file" id="picture" name="studentpicture" />
@Html.ValidationMessageFor(model => model.Picture)
</div>
<div class="editor-field">
@Html.DropDownListFor(model => model.City.CityId, ViewBag.cities as SelectList, "select city")
@Html.ValidationMessageFor(model => model.City.CityId)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
To run Aplication for first run change the following code in App_start=>routeconfig.cs
defaults: new { controller = "Student", action = "Create", id = UrlParameter.Optional }
change controller name and action name as you are using.
Action Create with form collection, add argument of class Student student.
Now run the application and fill values and click on create or submit button.
public ActionResult Create()
{
List cities = new List();
cities.Add(new Cities(1, "delhi"));
cities.Add(new Cities(2, "mumbai"));
cities.Add(new Cities(3, "chennai"));
cities.Add(new Cities(4, "kolkata"));
cities.Add(new Cities(5, "kohima"));
cities.Add(new Cities(6, "dehradun"));
ViewBag.cities = new SelectList(cities.ToArray(), "CityId", "CityName");
return View();
}
[HttpPost]
public ActionResult Create(Student student, FormCollection collection)
{
try
{
HttpPostedFileBase file2 = Request.Files["studentpicture"];
if (file2.ContentLength > 0)
{
string fileName = file2.FileName;
string path = System.IO.Path.Combine(Server.MapPath("~/Content"), fileName);
file2.SaveAs(path);
student.Picture = fileName;
}
List lstParam = new List();
lstParam.Add(new SqlParameter("@studentName", student.Name));
lstParam.Add(new SqlParameter("@studentImage", student.Picture));
lstParam.Add(new SqlParameter("@studentCity", student.City));
String connectionString = ConfigurationManager.ConnectionStrings["DataConnectionString"].ToString(); ;
SqlConnection connection = new SqlConnection(connectionString);
connection.Open();
SqlCommand command = new SqlCommand("INSERT INTO Table_Student(StudentName,Image,City) VALUES(@studentName, @studentImage,@studentCity)", connection);
command.CommandType = CommandType.Text;
int x = command.ExecuteNonQuery();
connection.Close();
return RedirectToAction("Index");
}
catch
{
return View();
}
}
Values been saved to database.
**Keywords and there meanings**
HttpPostedFileBase : Serves as the base class for classes that provide access to individual files that have been uploaded by a client.
ExecuteNonQuery : returns integer with no. of affected rows.
ActionResult :Represents the result of an action method.
Reading Operation
0 Comment(s)