Yes, we can perform CRUD operations in asp.net mvc framework. In this example I created one EmployeeController with Create,Edit,Delete,Details operations.
then Create a Model :
then change the Route : to Employee in Global.acax page
and index :
as well like this in every link of Details,Edit,Delete...also change them.
For every request
then Create a Model :
public class Employee
{
[Required]
[DisplayName("Employee
ID")]
public int EId { get; set; }
[Required]
[DisplayName("Employee
Name")]
public string EName {
get; set; }
[Required]
[DisplayName("Employee
Location")]
public string
ELocation { get; set;
}
}
new
{ controller = "Employee", action
= "Create", id = UrlParameter.Optional }
then goto every action and create their apporiate actions
Ex:
Index --->Add view -->Index--Stronglytyped view-->View content-->Ok
this is the same for all actions in the controller : EmployeeController .
this I am working with a static List<Employee> collection to peform to perform CRUD operations:
public class EmployeeController : Controller
{
Employee eobj;
static List<Employee> elist = new
List<Employee>();
public ActionResult
Index()
{
return
View(elist);
}
public ActionResult
Details(int id)
{
Employee empdetails = elist.First(t => t.EId ==
id);
return View(empdetails);
}
public ActionResult
Create()
{
// Employee eobj = new Employee { EId = 1, EName =
"AdrosTrolsen", ELocation = "USA" }; //design time asigned automatically
return View();
}
[HttpPost]
public ActionResult
Create(Employee ecollection)
{
try
{
eobj = new Employee
{ EId = ecollection.EId, EName = ecollection.EName, ELocation =
ecollection.ELocation };
elist.Add(eobj);
return RedirectToAction("Index");
}
catch
{
return View();
}
}
public ActionResult
Edit(int id)
{
Employee emp = elist.First(t=>t.EId == id);
return View(emp);
}
[HttpPost]
public ActionResult
Edit(int id, Employee
collection)
{
try
{
return RedirectToAction("Index");
}
catch
{
return View();
}
}
public ActionResult
Delete(int id)
{
Employee empdelete = elist.First(t => t.EId ==
id);
return View(empdelete);
}
[HttpPost]
public ActionResult
Delete(int id, Employee
collection)
{
try
{
Employee edelete = conobj.emps.Find(id);
conobj.emps.Remove(edelete);
conobj.SaveChanges();
conobj.emps.Remove(edelete);
conobj.SaveChanges();
return RedirectToAction("Index");
}
catch
{
return View();
}
}
}
<% foreach
(var item in
Model) { %>
<tr>
<td>
<%: Html.ActionLink("Edit",
"Edit", new
{ id=item.EId }) %> |
<%: Html.ActionLink("Details",
"Details", new { id=item.EId })%> |
<%: Html.ActionLink("Delete",
"Delete", new
{ id=item.EId })%>
</td>
<td>
<%: item.EId %>
</td>
<td>
<%: item.EName %>
</td>
<td>
<%: item.ELocation %>
</td>
</tr>
<% } %>
http://localhost:3866/Employee/Create
http://localhost:3866/Employee/Index
http://localhost:3866/Employee/Details
http://localhost:3866/Employee/Delete
automatically route is prepred as per our request// but one route only first request in global.asax.
No comments:
Post a Comment