MVC Framework-advanced example

Source: Internet
Author: User

In the first MVC Tutorial chapter, we learned how to interact with the MVC controller and the view. In this tutorial, we'll go a step further and learn how to create, edit, delete users, and view lists in our app using the model creation advanced application.

Here are the steps to create an advanced MVC application

1th Step: Select the File->new->project->asp.net MVC Web App. and named: Advancedmvcapplication. Click OK. In the next window, select the template as the Internet application and view engine for razor. Note that we are using a template instead of an empty application at this time.

This creates a new solution for the project, as shown in. Since we are using the default ASP. NET theme, it comes with sample views, controllers, models, and other files.

Build the solution and run the application to see its default output, as follows:

2nd Step: We will add a new schema that will define the user data structure. Right-click the Models folder, and then tap Add->class. Name Usermodel, and then click Add.

3rd Step: now copy the following code to the newly created UserModel.cs:

Using system;using system.componentmodel;using system.componentmodel.dataannotations;using System.Web.Mvc.Html; namespace advancedmvcapplication.models{public    class Usermodels    {        [Required] public        int Id {get; set ; }        [DisplayName ("First name")]        [Required (errormessage = "First name is Required")] public        string FirstName { Get Set }        [Required] public        string LastName {get; set;}                public string Address {get; set;}                [Required]        [Stringlength ()]        public string Email {get; set;}                [DataType (datatype.date)]        Public DateTime DOB {get; set;}                [Range (100,1000000)]        Public decimal Salary {get; set;}}    }

In the above code, we specify the user model to validate all parameters, their data types, and the required fields and lengths.

4th step: Now that we have the user model ready to save the data, now create a class file Users.cs which will contain methods for viewing users, adding, editing, and deleting users. Right-click the model, and then click Add->class. Named: Users. This creates the Users.cs class inside the models.

Copy the following code into the Users.cs class.

Using system;using system.collections.generic;using System.enterpriseservices;namespace        advancedmvcapplication.models{public class Users {public list userlist = new list ();            Action to get user details public usermodels GetUser (int id) {Usermodels usrmdl = null; foreach (Usermodels um in userlist) if (um.            ID = = id) usrmdl = um;        return usrmdl; }//action to create new user public void CreateUser (Usermodels usermodel) {Userlist.add (        Usermodel); }//action to udpate existing user public void UpdateUser (Usermodels usermodel) {foreach            (Usermodels usrlst in userlist) {if (usrlst. Id = = usermodel.id) {usrlst.                    Address = usermodel.address; Usrlst.                    DOB = Usermodel.dob; Usrlst.                    Email = Usermodel.email; usRlst.                    FirstName = Usermodel.firstname; Usrlst.                    LastName = Usermodel.lastname; Usrlst.                    Salary = usermodel.salary;                Break        }}}//action to delete exising user public void DeleteUser (Usermodels usermodel) {foreach (Usermodels usrlst in userlist) {if (usrlst).                    Id = = usermodel.id) {userlist.remove (USRLST);                Break }}}}} 

5th step: Once we have UserModel.cs and Users.cs, will increase the browsing model to view, add, edit and delete users. First, let's create a view to create a user. Right-click the Views folder and click Add->view.

In the next window, select the view name called Useradd, the View engine is razor, and select the Create a strongly typed view check box.

Click Add. By default this creates the following CSHML code, as follows:

@model advancedmvcapplication.models.usermodels@{viewbag.title = "UserAdd";} 

As you can see, this view contains all the property information for the field of validation messages, tags, etc., this view in our final application looks like this:

Like Useradd, now we'll add the following four view codes:

Index.cshtml

The view will show all the users that exist on our system on the index page.

@model ienumerable<advancedmvcapplication.models.usermodels>@{viewbag.title = "Index";}        

This view looks like the following in our final application:

Details.cshtml:

This view will show specific user details when we click on the user record.

@model advancedmvcapplication.models.usermodels@{viewbag.title = "Details";} 

This view looks like this in our final application:

Edit.cshtml:

This view will display an edit form for the details of the existing user.

@model advancedmvcapplication.models.usermodels@{viewbag.title = "Edit";} 

This view looks like the following in our application:

Delete.cshtml:

This view displays the form used to delete existing users.

@model advancedmvcapplication.models.usermodels@{viewbag.title = "Delete";} 

This view looks like this in our final application:

6th step: We have added models and views in the application. Now add a controller for the view. Right-click the Controllers folder, and then tap Add->controller. Named as: Usercontroller.

By default, the controller class is created with the following code:

Using system;using system.collections.generic;using system.linq;using system.web;using System.Web.Mvc;using Advancedmvcapplication.models;namespace advancedmvcapplication.controllers{Public   class Usercontroller: Controller    {        private static users _users = new users ();        Public ActionResult Index ()        {            return View (_users. userlist);}}}    

In the preceding code, the index method is rendered in the user list on the index page.

6th step: Right-click on the index method and select Create view to create the index page views (which will list all users and provide the option to create a new user).

7th step: Add the following code UserController.cs now. In this code, we create the action method for different user actions and return to create the corresponding view before returning.

We will add two methods for each operation: Get and post. When data is obtained, its httpget is used. HttpPost will be used to create/update data. For example, when we want to add a new user, we need a form to add the user, which is a get operation. When we fill out the form and submit these values, we need to use the Post method.

Action for index View public actionresult Index () {return view (_users. userlist);} Action for UserAdd view[httpget]public actionresult UserAdd () {return View ();} [Httppost]public actionresult UserAdd (usermodels usermodel) {_users.    CreateUser (Usermodel); Return View ("Index", _users. userlist);} Action for details view[httpget]public actionresult details (int id) {return View (_users. Userlist.firstordefault (x = x.id = = Id));} [Httppost]public actionresult Details () {return View ("Index", _users. userlist);} Action for Edit view[httpget]public actionresult edit (int id) {return View (_users. Userlist.firstordefault (X=>x.id==id));} [Httppost]public actionresult Edit (usermodels usermodel) {_users.    UpdateUser (Usermodel); Return View ("Index", _users.       userlist);} Action for delete view[httpget]public actionresult Delete (int id) {return View (_users. Userlist.firstordefault (x = x.id = = Id));} [Httppost]public actionresult Delete (usermodels usermodel) {_useRs.    DeleteUser (Usermodel); Return View ("Index", _users. userlist);} Sers. userlist);}

8th step: The last thing to do is to find the RouteConfig.cs file in the App_start folder and change the default controller.

defaults:new {controller = "User", action = "Index", id = urlparameter.optional}

9th step: The following is an advanced Application sample program to start and run. Now run the application. will be able to see such an application and can perform add, view, edit, delete users, because in front of have seen all the features

MVC Framework-advanced example

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.