You are on page 1of 17

Crud_operation

Create table dept_tbl with 2 fields (deptid primary key autoincrement,dname).

Add some rows like

Now create table emp_data as follow:


Eid having primary key and identity true. Add foreign key for deptno .
Now create new mvc project.

Right click on model add ado.entity data model->select sql server-select all tables. Build solution.

Bind model with controller (using projectname.Models;)

Create object of databaseentity.

In home controller create one actionResult ShowALLEmp(){

Var a=db.emp_data.tolist();

Return View(a);

}
create view with list template.select proper model class and datacontext class.

public ActionResult Index()

return View(db.emp_data.ToList());

Now create action result for newemp

public ActionResult addnewemp()

var a = db.dept_tbl.ToList();

ViewBag.deptlist = new SelectList(a, "deptid", "dname");

emp_data e = new emp_data();

return View();

Create view with create template,required model class.

We will make some changes for deptno field as follows

<div class="form-group">

@Html.LabelFor(model => model.deptno, "deptno", htmlAttributes: new { @class = "control-


label col-md-2" })

<div class="col-md-10">

@Html.DropDownListFor(m=>m.deptno, ViewBag.deptlist as SelectList, "select dept",


htmlAttributes: new { @class = "form-control" })

@Html.ValidationMessageFor(model => model.deptno, "", new { @class = "text-danger" })

</div>

</div>

For city field

<div class="form-group">

@Html.LabelFor(model => model.city, htmlAttributes: new { @class = "control-label col-md-


2" })

<div class="col-md-10">
@Html.DropDownListFor(model => model.city, new SelectList(new[] { "Mumbai", "Pune",
"Satara" }), "--select city--", new { htmlAttributes = new { @class = "form-control" } })

@Html.ValidationMessageFor(model => model.city, "", new { @class = "text-danger" })

</div>

</div>

For doj

We want calendar control for this

Right click on project name –manage NuGet package—in brows tab serach for bootstarp-
datepicker.js—install it

Drag and drop in our newempview page,

<script src="~/Scripts/jquery-3.4.1.min.js"></script>

<script src="~/Scripts/bootstrap-datepicker.js"></script>

<script>

$('.datepicker').datepicker({

changeMonth: true,

changeYear: true,

format: "dd/MM/yyyy",

language: "tr",

todayHighlight: true

});

</script>

Make some changes for doj field as-

<div class="form-group">

@Html.LabelFor(model => model.doj, htmlAttributes: new { @class = "control-label col-md-


2" })

<div class="col-md-10">

@Html.EditorFor(model => model.doj, new { htmlAttributes = new { @class = "form-control


datepicker" } })

@Html.ValidationMessageFor(model => model.doj, "", new { @class = "text-danger" })


</div>

</div>

And we also add format type in our class.

[Required(ErrorMessage = "plz select date of joining")]

public Nullable<System.DateTime> doj { get; set; }

--

Now for emp_img

We want upload file control so ….

<div class="form-group">

@Html.Label("emp img", htmlAttributes: new { @class = "control-label col-md-2" })

<div class="col-md-6">

<div class="form-group">

<span class="btn btn-info fileinput-button show">

<img src="~/App_img/defaultuser.png" style="margin:10px" height="100" width="100"


id="imgpre" />

<span>Add Image File...</span>

<input type="file" name="uploadimg" class="form-control"


accept="image/jpeg,image/png" required onchange="showimgpreview(this,
document.getElementById('imgpre'))" />

</span>

</div>

</div>

</div>

When we upload any image I want to show preview of that image .so for that I am creating one
javascript function showimgpreview as follows.
<script language="Javascript">

function showimgpreview(imageuploader, imgpre) {

if (imageuploader.files && imageuploader.files[0]) {

var reader = new FileReader();

reader.onload = function (e) {

$(imgpre).attr('src', e.target.result);

reader.readAsDataURL(imageuploader.files[0]);

</script>

Now for validation I add some data annotation to my fields as follows

using System.ComponentModel.DataAnnotations;

public partial class emp_data

public int eid { get; set; }

[Required (ErrorMessage ="plz enter first name")]

public string fname { get; set; }

[Required(ErrorMessage = "plz enter last name")]

public string lname { get; set; }

[Required(ErrorMessage = "plz enter age")]

public Nullable<int> age { get; set; }

[Required(ErrorMessage = "plz enter city")]

public string city { get; set; }

[Required(ErrorMessage = "plz select date of joining")]


public Nullable<System.DateTime> doj { get; set; }

[Required(ErrorMessage = "plz enter email")]

[RegularExpression("[a-z0-9._%+-]+@[a-z0-9.-]+\\.[a-z]{2,4}", ErrorMessage = "Please enter


correct email")]

public string email { get; set; }

[Required(ErrorMessage = "plz enter mobile")]

[RegularExpression(@"^([0-9]{10})$", ErrorMessage = "Please Enter Valid Mobile Number.")]

public string mobile { get; set; }

[Required(ErrorMessage = "plz enter name")]

public Nullable<int> deptno { get; set; }

public string emp_img { get; set; }

public virtual dept_tbl dept_tbl { get; set; }

public System.Web.HttpPostedFileBase uploadimg { get; set; }

public emp_data()

emp_img = "~/App_img/defaultuser.png";

} }

My create page will look like this:


Now one more change I have to make in web config.we are going post image file it might be
long size,so to allow this….

<system.web>

<compilation debug="true" targetFramework="4.7.2" />

<httpRuntime targetFramework="4.7.2" maxRequestLength="100000" />

</system.web>

Now form is ready ..we will create post action as follows:

[HttpPost]

public ActionResult addnewemp(emp_data e)

emp_data e1 = new emp_data();

e1.fname = e.fname;

if (e.uploadimg != null)

string fileName = Path.GetFileNameWithoutExtension(e.uploadimg.FileName);

fileName = fileName.Substring(1, 3);

string extention = Path.GetExtension(e.uploadimg.FileName);

fileName = fileName + DateTime.Now.ToString("yymmssfff") + extention;

e1.emp_img = "~/App_img/" + fileName;


e.uploadimg.SaveAs(Path.Combine(Server.MapPath("~/App_img/"), fileName));

e1.age = e.age;

e1.city = e.city;

e1.deptno = e.deptno;

e1.doj = e.doj;

e1.email = e.email;

e1.lname = e.lname;

e1.mobile = e.mobile;

db.emp_data.Add(e1);

db.SaveChanges();

return RedirectToAction("Index");

Now for update:

public ActionResult updateemp(int id)

var a = db.dept_tbl.ToList();

ViewBag.deptlist = new SelectList(a, "deptid", "dname");

var e = db.emp_data.Where(x => x.eid == id).FirstOrDefault();

return View(e);

@model crud_example.Models.emp_data

@{

ViewBag.Title = "updateemp";

}
<h2>updateemp</h2>

@using (Html.BeginForm())

@Html.AntiForgeryToken()

<div class="form-horizontal">

<h4>emp_data</h4>

<hr />

@Html.ValidationSummary(true, "", new { @class = "text-danger" })

@Html.HiddenFor(model => model.eid)

<div class="form-group">

@Html.LabelFor(model => model.fname, htmlAttributes: new { @class = "control-label


col-md-2" })

<div class="col-md-10">

@Html.EditorFor(model => model.fname, new { htmlAttributes = new { @class =


"form-control" } })

@Html.ValidationMessageFor(model => model.fname, "", new { @class = "text-


danger" })

</div>

</div>

<div class="form-group">

@Html.LabelFor(model => model.lname, htmlAttributes: new { @class = "control-label


col-md-2" })

<div class="col-md-10">

@Html.EditorFor(model => model.lname, new { htmlAttributes = new { @class =


"form-control" } })

@Html.ValidationMessageFor(model => model.lname, "", new { @class = "text-


danger" })
</div>

</div>

<div class="form-group">

@Html.LabelFor(model => model.age, htmlAttributes: new { @class = "control-label


col-md-2" })

<div class="col-md-10">

@Html.EditorFor(model => model.age, new { htmlAttributes = new { @class =


"form-control" } })

@Html.ValidationMessageFor(model => model.age, "", new { @class = "text-danger"


})

</div>

</div>

<div class="form-group">

@Html.LabelFor(model => model.city, htmlAttributes: new { @class = "control-label


col-md-2" })

<div class="col-md-10">

@Html.DropDownListFor(model => model.city, new SelectList(new[] { "Mumbai",


"Pune", "Satara" }), "--select city--", new { htmlAttributes = new { @class = "form-control" } })

@Html.ValidationMessageFor(model => model.city, "", new { @class = "text-danger"


})

</div>

</div>

<div class="form-group">

@Html.LabelFor(model => model.doj, htmlAttributes: new { @class = "control-label


col-md-2" })

<div class="col-md-10">

@Html.EditorFor(model => model.doj, new { htmlAttributes = new { @class = "form-


control datepicker" } })

@Html.ValidationMessageFor(model => model.doj, "", new { @class = "text-danger"


})

</div>
</div>

<div class="form-group">

@Html.LabelFor(model => model.email, htmlAttributes: new { @class = "control-label


col-md-2" })

<div class="col-md-10">

@Html.EditorFor(model => model.email, new { htmlAttributes = new { @class =


"form-control" } })

@Html.ValidationMessageFor(model => model.email, "", new { @class = "text-


danger" })

</div>

</div>

<div class="form-group">

@Html.LabelFor(model => model.mobile, htmlAttributes: new { @class = "control-


label col-md-2" })

<div class="col-md-10">

@Html.EditorFor(model => model.mobile, new { htmlAttributes = new { @class =


"form-control" } })

@Html.ValidationMessageFor(model => model.mobile, "", new { @class = "text-


danger" })

</div>

</div>

<div class="form-group">

@Html.LabelFor(model => model.deptno, "deptno", htmlAttributes: new { @class =


"control-label col-md-2" })

<div class="col-md-10">

@Html.DropDownListFor(m => m.deptno, ViewBag.deptlist as SelectList, "select


dept", htmlAttributes: new { @class = "form-control" })

@Html.ValidationMessageFor(model => model.deptno, "", new { @class = "text-


danger" })

</div>

</div>
<div class="form-group">

<label class="col-form-label" for="DateOfBirth"> Employee Image </label>

@Html.ValidationMessageFor(model => model.emp_img, "", new { @class = "text-


danger" })

<div class="col-md-10">

<div class="form-group">

<span class="btn btn-info fileinput-button show">

@if (Model.emp_img == null)

<img src="~/App_img/defaultuser.png" style="margin:10px" height="100"


width="100" id="imgpre" />

<span>Add Image File...</span>

<input type="file" name="uploadimg" class="form-control"


accept="image/jpeg,image/png" required onchange="showimgpreview(this,
document.getElementById('imgpre'))" />

else

<img src="@Url.Content(Model.emp_img)" style="margin:10px"


height="100" width="100" id="imgpre" />

<span>Add Image File...</span>

<input type="file" name="uploadimg" class="form-control"


accept="image/jpeg,image/png" onchange="showimgpreview(this,
document.getElementById('imgpre'))" />

</span>

</div>

</div>
</div>

<div class="form-group">

<div class="col-md-offset-2 col-md-10">

<input type="submit" value="Save" class="btn btn-default" />

</div>

</div>

</div>

<div>

@Html.ActionLink("Back to List", "Index")

</div>

@section Scripts {

@Scripts.Render("~/bundles/jqueryval")

<script src="~/Scripts/jquery-3.4.1.min.js"></script>

<script src="~/Scripts/bootstrap-datepicker.js"></script>

<script>

$('.datepicker').datepicker({

changeMonth: true,

changeYear: true,

format: "dd/MM/yyyy",

language: "tr",

todayHighlight: true

});

</script>
<script language="Javascript">

function showimgpreview(imageuploader, imgpre) {

if (imageuploader.files && imageuploader.files[0]) {

var reader = new FileReader();

reader.onload = function (e) {

$(imgpre).attr('src', e.target.result);

reader.readAsDataURL(imageuploader.files[0]);

</script>

I hope you will try for update and delete……..

Now we will try for pagination.

public ActionResult Index(int pagenumber = 1)

var emp = db.emp_data.ToList();

ViewBag.totalpage = Math.Ceiling(emp.Count / 2.0);

emp = emp.Skip((pagenumber - 1) * 2).Take(2).ToList();

return View(emp);

And in view

@{

double totalpages = ViewBag.totalpage;

for (int i = 1; i <= totalpages; i++)

<ul class="pagination">

<li>
@Html.ActionLink(i.ToString(), "Index", new { pagenumber = i })

</li>

</ul>

You might also like