The first entry field -- ASP. NET MVC4 Web application development II to achieve simple addition, deletion, modification, and query, -- asp. netmvc4

Source: Internet
Author: User

The first entry field -- ASP. NET MVC4 Web application development II to achieve simple addition, deletion, modification, and query, -- asp. netmvc4

Create a blank MVC application for ASP. NET MVC4 Web Application

Simple logon is implemented in ASP. NET MVC4 Web application development.

2016-07- 1. Create M002AdminDemo. csRight-click [Models] --> Add --> class
Using System; using System. collections. generic; using System. linq; using System. web; namespace Ddup. models {/// <summary> /// administrator model demonstration /// </summary> public class M002AdminDemo {/// <summary> /// define a query for all administrators // </summary> /// <returns> </returns> public static IEnumerable <T001Admin> GetAll () {DdupEntities db = new DdupEntities (); return db. t001Admin ;} /// <summary> /// define a method for finding the corresponding administrator by id /// </summary> /// <param name = "id"> </param >/// <returns> </returns> public static T001Admin GetById (int id) {DdupEntities db = new DdupEntities (); return db. t001Admin. firstOrDefault (m => m. id = id );}}}
2. Create an administrator view model for Vm002. Right-click "cs" and choose "ViewModel"> "add"> "class ".

 

Using System; using System. collections. generic; using System. linq; using System. web; // call the using System assembly required for data annotation. componentModel. dataAnnotations; namespace Ddup. models. viewModel {public class Vm002 adds an administrator view model {// required indicates a Required parameter. ErrorMessage returns the error message [required (ErrorMessage = "{0}, cannot be blank")] // stringlength defines the input character range (max, min, error) [StringLength (20, MinimumLength = 10, errorMessage = "Enter {2} to {1} characters")] // define the Name of the attribute displayed on the page [Display (Name = "account")] public string Account {get; set;} [Required (ErrorMessage = "{0}, cannot be blank")] [StringLength (20, MinimumLength = 10, errorMessage = "Enter {2} to {1} characters")] [Display (Name = "Password")] public string Password {get; set ;} [Required (ErrorMessage = "{0}, cannot be blank")] [StringLength (4, MinimumLength = 2, errorMessage = "Enter {2} to {1} characters")] [Display (Name = "Name")] public string Name {get; set ;} /// <summary> /// defines an empty constructor in the Vm002 new Administrator view model class /// </summary> public Vm002 new Administrator view model () {Account = ""; Password = ""; // for the subsequent (Create) demonstration, set the Name initialization value to Ddup Name = "Ddup ";} /// <summary> /// defines the method for inserting new data into the database through EF. /// </summary> public void Save () {using (DdupEntities db = new DdupEntities () {var t001 = new T001Admin () {Account = this. account, Password = this. password, Name = this. name}; db. t001Admin. add (t001); db. saveChanges ();}}}}

 

3. Right-click the C02AdminController. cs controller and choose Controllers> Add controller> Empty MVC5 controller.

 

Using System; using System. collections. generic; using System. linq; using System. web; using System. web. mvc; using Ddup. models; using Ddup. models. viewModel; namespace Ddup. controllers {public class C02AdminController: Controller {// <summary> /// use the GetAll () method, return all administrator information /// </summary> /// <returns> </returns> public ActionResult Index () {return View (M002AdminDemo. getAll ();} // <summary> // use GetById () Method, obtain the detailed information of the corresponding administrator by passing the id /// </summary> /// <param name = "id"> </param> /// <returns> </returns> public ActionResult Details (int id) {var model = M002AdminDemo. getById (id); if (model = null) return View ("Error"); return View (model );} /// <summary> /// define the new get action and call the empty constructor of the new Administrator view model in Vm002, initialize //// </summary> /// <returns> </returns> public ActionResult Create () {// through this action, the initial values of the page Name will be added later with Vm002 The initialization values defined by // in the empty constructor of the new Administrator view model are the same. Return View (new Vm002 new Administrator View model ();} /// <summary> // defines the new action of post. When the form submission method in View is POST, this action will be used to perform the operation // </summary> /// <param name = "model"> </param> /// <returns> </returns> [HttpPost] public ActionResult Create (Vm002 adds an administrator view model) {// try, catch exception capture try {// determine whether the model status is valid. Here, we will judge based on the data comment of each attribute in the new Administrator view model of Vm002, whether the input value is valid if (ModelState. isValid) {// call the Save () model defined in the new Administrator view model of Vm002. save ();// Return View ("Index"); // return Redirect ("~ /C02Admin/Index "); return RedirectToAction (" Index ") ;}} catch (Exception ex) {// Add the caught Exception information, or specify the keyword (for example, "Name"). In the future, the corresponding error information ModelState will be output in the View. addModelError ("", ex. message);} return View (model);} public ActionResult Edit (int id) {var model = M002AdminDemo. getById (id); if (model = null) return View ("Error "); // ViewData, one of the value passing methods between the foreground and the background, // transmits the model data found by id to the model ViewData associated with the view data. model = model; return View (Model);} [HttpPost] public ActionResult Edit (int id, FormCollection collection) {try {if (ModelState. isValid) {DdupEntities db = new DdupEntities (); var model = db. t001Admin. firstOrDefault (m => m. id = id); # region 1.0 update the model's keyword field value (all) string [] strArr = collection. allKeys; TryUpdateModel (model, strArr); # endregion # region 2.0 update the model's keyword field value (select the keyword field to be updated) // TryUpdateModel (model, new string [] {"Account", "Password", "Name"}); # endregion db. saveChanges (); return RedirectToAction ("Index") ;}} catch (Exception ex) {ModelState. addModelError ("", ex. message) ;}return View () ;}public ActionResult Delete (int id) {try {DdupEntities db = new DdupEntities (); var t001 = db. t001Admin. firstOrDefault (m => m. id = id); if (t001! = Null) {db. t001Admin. remove (t001); db. saveChanges (); return RedirectToAction ("Index") ;}} catch (Exception ex) {ModelState. addModelError ("", ex. message) ;}return View ();}}}
4. Create a view and add it. Return to the Index view of all administrators.

Add and return the Administrator Details View of the corresponding id

Add View

Add edit View

 

5. Test the addition, deletion, modification, and query functions we have created.

 

I am a beginner. If you have any questions, please forgive me. I hope you can give me more comments. Thank you !!!

========================================================== ========================================================== ========================

Author: Cheng
Source: http://rcddup.cnblogs.com
This article was originally published by Cheng and published to the blog Park. You are welcome to repost it, but the author and source must be clearly indicated on the article page. Thank you very much!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.