Recently I saw a thread in the C# Corner Forums. Many people like to do doing insert, update and delete in a single View, in other words similar to ASP.NET. So I decided to write an article on this topic.
By default ASP.NET MVC does not support this approach. We need to implement some tricks to do this.
Step 1
Create the blank application like this:
Step 2
Create the database table like this:
Step 3
In the Model layer, create the model using an EF database first approach like this:
Step 4
Now create a blank Emp controller like this:
Step 5
Add a class, HttpParamActionAttribute, in the solution like this:
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Reflection;
- using System.Web;
- using System.Web.Mvc;
-
- namespace EmpDemoInMVC
- {
- public class HttpParamActionAttribute : ActionNameSelectorAttribute
- {
- public override bool IsValidName(ControllerContext controllerContext, string actionName, MethodInfo methodInfo)
- {
- if (actionName.Equals(methodInfo.Name, StringComparison.InvariantCultureIgnoreCase))
- return true;
-
- var request = controllerContext.RequestContext.HttpContext.Request;
- return request[methodInfo.Name] != null;
- }
- }
- }
Note: We are writing this class to fire the multiple Submit button events from a single view.
Step 6
Write the Action Method in the Controller for the insert/update/delete and fetch functionalities like this:
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
- using EmpDemoInMVC.Models;
- using System.Data.Entity;
-
- namespace EmpDemoInMVC.Controllers
- {
- public class EmpController : Controller
- {
-
- EmpEntities db = new EmpEntities();
-
-
-
- public ActionResult Index(int? id)
- {
- ViewBag.Operation = id;
- ViewBag.Name = db.tblEmps.ToList();
- tblEmp objEmp = db.tblEmps.Find(id);
- return View(objEmp);
- }
-
- [HttpPost]
- [HttpParamAction]
- [ValidateAntiForgeryToken]
- public ActionResult Create(tblEmp objEmp)
- {
- if (ModelState.IsValid)
- {
- db.tblEmps.Add(objEmp);
- db.SaveChanges();
- }
- return RedirectToAction("Index");
- }
-
- [HttpPost]
- [HttpParamAction]
- [ValidateAntiForgeryToken]
- public ActionResult Update(tblEmp objEmp)
- {
- if (ModelState.IsValid)
- {
- db.Entry(objEmp).State = EntityState.Modified;
- db.SaveChanges();
- }
- return RedirectToAction("Index", new { id = 0 });
- }
-
- public ActionResult Delete(int id)
- {
- tblEmp objEmp = db.tblEmps.Find(id);
- db.tblEmps.Remove(objEmp);
- db.SaveChanges();
- return RedirectToAction("Index", new { id = 0 });
- }
- }
- }
Step 7
Create the Empty View from the controller like this:
Step 8
Now write the HTML code as per as our requirements like this:
Summary
In this article we showed that we are using only one view for doing doing insert, update, delete and fetch functionality. If you like to implement an entry screen similar to the ASP.NET style then you can use this approach.