Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is ASP.NET MVC?

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

The main content of this article is to explain "what is ASP.NET MVC". Interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn what ASP.NET MVC is.

First of all, let's take a look at the program provided by Imar, which is a typical add, delete, check and modify program that allows users to manage contacts, including their address, phone number, and email. It can add, delete, check, and change any entity.

The entities included in the program are: ContactPersons,PhoneNumbers,AddressesEmailAddresses. They all belong to the business object (BO) layer of the program. Each of the above classes contains properties that can be obtained or assigned, but does not contain any methods. All methods are stored in the corresponding classes in the business logic layer (BLL). The entity and entity manger in the business object layer and the business logic layer have an one-to-one relationship. The methods contained in the class in the business logic layer will return the instance of the business object layer (BO), or a collection of instances, or save the instance (update or add), or delete the instance. The business logic layer (BLL) can also contain some code for business rule validation and security checking. However, these will not be added in this article for the sake of simplicity. If you are interested in business rules and security, you can go to the 6partseries of the Imar article.

The last layer is the data access layer (DAL). Similarly, the classes in the Dal layer have an one-to-one relationship with the classes in the business logic layer (BLL), and the methods in the relevant DAL layer are called in the classes in the BLL layer. Of these layers, only the DAL layer needs to know what technology (linq,entityframework..) to use to hold the business entity. In this example, the SqlServerExpress database and ADO.NET are used. The idea of this layering is that if you need to change the data source (XML,oracle, or even WebService or even LinqtoSql or other ORM framework), because the signature of the DAL layer to the BLL layer is the same, you only need to change the DAL layer. In order to ensure that all DAL implementations have the same signature, you can use the interface. But I think it may be the topic discussed in the future post.

MVC framework

To put it simply, M stands for Model, which also contains BO,BLL,DAL, V stands for View, which is also the part of UI-related development, or what users see. C is the abbreviation of Controller, and it is also the part that controls user requests and program responses. If the user clicks a button pointing to a specific address, the request matches the Action (method of the class) of the Controller, while the Action processes the request and returns the response. It is usually a new View, or an update of an existing View.

Let's create a MVC application with VisualStudio and delete the default View and Controller, then copy the Bo,Bll and DAL from Imar's program into the Model of this MVC program, and I also copy the database file and Style.css of the response.

I also made some other changes to add the database connection string to the Web.Config. In addition, I adjusted the namespace of the copied code and upgraded the DAL layer code to 3. 0. Although this is not necessary. After doing this, I press Ctrl+Shift+F5 to test whether the compilation is successful.

Controller

Add four Controller (the default Controller that comes with VisualStudio has been removed) to match the four entity classes. They are: ContactController,PhoneController,AddressControllerandEmailController.

Each Controller contains four Action:List,Add,Edit,andDelete. First, you need to register these routes for these Action in Global.exe.

Public static void RegisterRoutes (RouteCollection routes) {routes.IgnoreRoute ("{resource} .axd / {* pathInfo}"); routes.MapRoute ("Default", "{controller} / {action} / {id}", new {controller = "Contact", action = "List", id = ""});}

The default View displays all contacts, and the GetList () method in the ContactPersonManager class in the BLL layer fetches the data of all contacts. The response List () Action code is as follows:

Public ActionResult List () {var model = ContactPersonManager.GetList (); return View (model);}

Strongly typed View

I use strongly typed View throughout the example code, because not only can I use the benefits of intellisense, but I don't have to rely on ViewData that uses String as the index value. To make the code more orderly, I added some namespaces to the nodes in web.config, which is how I replace the Imar code:

The above code means that I can access the above namespace anywhere in the program. The type returned by the above GetList () method is ContactPersonList, which is a collection of ContactPerson objects. The Page declaration in the View that displays the List is as follows:

I think you've noticed that I used MasterPage, and with MasterPage, I borrowed the Css file from the Imar example code. The HTML used to display ContactPerson objects is as follows:

Id Full Name Date of Birth Type Addresses Email Phone Numbers Edit Delete No Contacts Yet

I think you can see the benefits of strongly typed View, the type of Model is ContactPersonList, so you can use the properties of ContactPersonList without casting, and casting errors can only be found at run time, so it saves a lot of trouble.

I cheated a little while doing Html. I could have used the view automatically generated by vs to list, but I didn't. Because I need a html that matches Imar's css file. So I ran the imar program, looked at the source code in the browser, and copied the generated html. Imar uses GridView to generate the list, so CSS is embedded in the html code at run time. I moved the css code to an external css file. And add some additional styles to the and elements, which you can find in the download link of the code.

I haven't added the title attribute to some table cells yet. These contain links to other action. I hope the page will not postback when users browse the phone book or edit or delete it. In other words, I want my website to be ajax. The title attribute comes into play. The ". Link" css selector makes ordinary text look like a hyperlink, that is, a small hand when there is an underscore and a mouse hover.

JQuery Ajax

Before we delve into the code related to the ajax function, the following three lines of code need to be added to the html:

Are you sure about this?

The first line of code acts as a button that allows the user to add a new contact, the second line of code is an empty div to facilitate the subsequent display of information, and the third line of code is part of the jQuerymodal prompt verification dialog box that prompts the user whether to delete a record.

You also need to add three js files to the page, the first is the main jQuery file, the other two are the core js of jQueryUI, and the JS in the datepicker and modaldialog sections:

Here is our generated list display view and the complete JS code:

$(function () {/ / row colours $('tr:even'). Css (' background-color','# EFF3FB'); $('tr:odd'). Css (' background-color','# FFFFFF'); / / selected row managment $('tr') .click (function () {$(' tr') .each (function () {$(this) .removeClass ('SelectedRowStyle')) }); $(this) .addClass ('SelectedRowStyle');}); / / hide the dialog div $(' # dialog'). Hide (); / / set up ajax to prevent caching of results in IE $.ajaxSetup ({cache: false}) / / add an onclick handler to items with the "link" css class $('.link'). Live ('click', function (event) {var id = $.trim ($(' td:first', $(this). This ('tr')). Text ()); var loc = $(this) .attr (' title') / / check to ensure the link is not a delete link if (loc.lastIndexOf ('delete') = =-1) {$.get (loc +' /'+ id, function (data) {$('# details') .html (data);}) / / if it is, show the modal dialog} else {$('# dialog') .dialog ({buttons: {'Confirm': function () {_ window.location.href = loc +' /'+ id;}, 'Cancel': function () {$(this) .subscription (' close')) }); $('# dialog'). Dialog ('open');}}); / / add an onclick event handler to the add contact button $(' # addContact') .click (function () {$.get ('Contact/Add', function (data) {$(' # details') .html (data)) })

The above code looks daunting, but in fact, with jQuery, it's very simple. And I added comments in many places in the above code. At the beginning, the code replaced the interlaced color displayed by the data source control by default with the js code. Then I added code that makes it possible to change color when a click line is clicked. Then the following code prevents IE from caching the page. If you do not disable IE caching, you will hit the wall because the database changes but the page does not change after editing or deleting.

The next code is even more interesting, relying on the live () method to make sure that all matching elements in the $selector have corresponding events attached, regardless of whether the element currently exists on the page or not. For example, when you click on the Addresses link, the corresponding results will appear in another table:

As you can see in the figure above, the table contains edit and delete links, and if you do not use the live () method, the corresponding links will not be appended to events. All elements with class as link are delegated to the click event. This event first gets the id of the current entry. Take the ContactPerson table as an example, this id is ContactPersonId. In the corresponding subtable, the id will be the phone number or the email address. These need to be passed to controlleraction as parameters for editing, deletion, or display.

Now you can see why I add the title attribute to each cell. The title property contains relevant route information, while the full url appends id to route as a url. Then, the above js does a check to see if the route message contains delete, and if it does, a dialog box pops up to prompt the user whether to delete it. Look, isn't it easy? Finally, the code adds a click event to the add contact button.

Add contacts and customize ViewModels

When using to add a record, it is common practice to provide a form that contains a series of input boxes. For most properties of the ContactPerson class, they can be assigned directly, such as last name, first name, and birthday. But one of the attributes cannot be assigned directly-the Type property, which is selected from the enumerated types in PersonType.cs (friends, colleagues, etc.). This means that users can only choose from a limited number of options. You can do this in DropDwonList, but the ContactPerson object does not contain all the options for enumerated types, so we can only provide a custom version of the ContactPerson class to pass to View. This is why custom ViewModel is used.

I have seen a lot of discussion about where to put ViewModels in the program. Some people think that custom ViewModels is part of Model, but I think it is closely related to View. ViewModels is not an essential part of MVC programs and cannot be taken, so it should not be placed in the central area of Model. I put all the ViewModel in a created ViewModel folder, and the source code for ContactPersonViewModel.cs is as follows:

Using System; using System.Collections.Generic; using System.Web.Mvc; namespace ContactManagerMVC.Views.ViewModels {public class ContactPersonViewModel {public int Id {get; set;} public string FirstName {get; set;} public string MiddleName {get; set;} public string LastName {get; set;} public DateTime DateOfBirth {get; set;} public IEnumerable Type {get; set;}

Looking at the last property of the above class, I set the type property to IEnumerable so that I can bind the Type to the Html.DropDownList in the View.

Correspondingly, add two action to the Controller, the first action uses the AcceptVerbs (HttpVerbs.Get) tag, the second action uses the AcceptVerbs (HttpVerbs.Post) tag, the first method is used to pass values from the server to the client, and the first method handles the data submitted from the form.

The first few lines of code in the first action above convert the ContactType enumerated type into an array. Each element in the array is an anonymous object containing id and name attributes, id is the enumerated value, Name is the enumerant value that matches the corresponding enumeration, ContactPersonViewModel is then initialized and the Type attribute is assigned the corresponding type. I use PartialView to add contacts and use strong typing of ContactPersonViewModel type, and the code corresponding to the View section is as follows:

In the top code I use jQueryUI's Datepicker plug-in as the selection of the DateOfBirth input box, and the second parameter of DateOfBirth ensures that the textbox is empty in the initial state. In addition, all input boxes have the same corresponding property name for ContactPerson to ensure that the default modelbinder is error-free, and MVC automatically binds the ContactType enumeration.

The method responsible for responding to the Post request can automatically match the value of Request.Form with the corresponding property of the ContactPerson object, then call the Save () method of the BLL layer, and then RedicrectToAction will refresh the page and finally call the action of List.

Edit a contact

We saw earlier how jQuery calls the Edit action and passes the edited person's id as a parameter, and then id is used to fetch contact details from the database through the well-known bll call DAL.

$(function () {$('# DateOfBirth') .datepicker ({dateFormat: 'yy/mm/dd'});}) Name Middle Name Last Name Date of Birth Type

The key difference is that DateOfBirth includes a more recognizable way to transform birthday information, and a Html.Hidden () has been added near the submit button to save the id of the edited user. Of course, the action property of form must be different from the View of Add. You can add a parameter to Form to tell Action whether it is AddView or EditView, which reduces code duplication, but in the sample code I still divide them into different action to make the division of responsibilities clearer.

Delete a contact

Deleting an action is much easier, and you don't need the View associated with it. Simply re-invoke the List action, and the deleted data no longer exists. The above code is where I make changes to BLL and DAL. The argument to the original ContactPersonManager.Delete () method is an instance of Person, while in DAL, only id is the parameter. I don't see the point of passing the whole object to BLL, but BLL only passes the unique ID of the object to DAL, so I change the code of BLL to accept parameters of type int, which makes it easier to write. When the delete link is clicked, call jQuery's confirmationmodaldialog:

If you click cancel, nothing happens, and if you click OK, the link points to the deleteaction of the response.

Manage collection

All collections-PhoneNumberList,EmailAddressLIst,AddressList are managed in the same way. So, I just picked EmailAddressLIst as an example to illustrate the method, and you can download the sample code to see other parts. The above method uses the contact's id as the contact and returns a custom ViewModel-EmailAddressListViewModel. This is also how to transfer the contact's id to View:

$(function () {$('# add') .click (function () {$.get ('Email/Add/', function (data) {$(' # details') .html (data);});}) Contact Person Id Email Type Edit Delete No email addresses for this contact

You can see that the add method requires ContactPersonID as a parameter, and we need to make sure that we can add new contacts to the response contact list. The same is true of editing and deleting methods-- the id parameter is passed to the relevant action through url. All cells have a title property, so you can use the previously deployed live () method:

[AcceptVerbs (HttpVerbs.Get)] public ActionResult Add (int id) {var contactTypes = Enum.GetValues (typeof (ContactType)) .Cast () .Select (c = > new {Id = c, Name = c.ToString ()}) Var model = new EmailAddressViewModel {ContactPersonId = id, Type = new SelectList (contactTypes, "ID", "Name")}; return PartialView ("Add", model);} [AcceptVerbs (HttpVerbs.Post)] public ActionResult Add (EmailAddress emailAddress) {emailAddress.Id =-1; EmailAddressManager.Save (emailAddress) Return RedirectToAction ("List", new {id = emailAddress.ContactPersonId});}

The purpose of creating a custom ViewModel is to add or edit an existing EmailAddress, including some properties that bind the IEnumerable collection to the Typedropdown. The above two Add differ in their returns, the first returning partialview and the second returning the action of List.

Each selection in the collection will initially set id to-1 to ensure compliance with the "Upsert" stored procedure, because Imar uses the same stored procedure for adding and deleting, and if it is not set to-1, the currently newly created contact will update the contact in the database.

The above jQuery code is responsible for submitting form.jQuery to htmlbutton (rather than inputtype= "submit") via Ajax to attach events, and then serializing the content in the page and sending it through a post request to an action named add () decorated with the appropriate AcceptVerbs tag.

Edit and delete EmailAddress objects

The action involved in editing the EmailAddress object is very similar to the one mentioned earlier, but there are still two action, one for processing get requests and the other for processing post requests:

AcceptVerbs (HttpVerbs.Get)] public ActionResult Edit (int id) {var emailAddress = EmailAddressManager.GetItem (id); var contactTypes = Enum.GetValues (typeof (ContactType)) .cast () .Select (c = > new {Id = c, Name = c.ToString ()}) Var model = new EmailAddressViewModel {Type = new SelectList (contactTypes, "ID", "Name", emailAddress.Type), Email = emailAddress.Email, ContactPersonId = emailAddress.ContactPersonId, Id = emailAddress.Id}; return View (model);} [AcceptVerbs (HttpVerbs.Post)] public ActionResult Edit (EmailAddress emailAddress) {EmailAddressManager.Save (emailAddress); return RedirectToAction ("List", "Email", new {id = emailAddress.ContactPersonId});}

The following partialView code should be familiar by now:

$(function () {$('# save') .click (function () {$.ajax ({type: "POST", url: $("# EditEmail"). Attr ('action'), data: $("# EditEmail"). Serialize (), dataType: "text/plain" Success: function (response) {$("# details") .html (response) }); Email: Type:

The above code is still very similar to AddView, except for the html hidden domain that contains EmailAddress.Id, which is to ensure that the correct email address is updated, and Deleteaction does not have to explain too much.

Public ActionResult Delete (int id) {EmailAddressManager.Delete (id); return RedirectToAction ("List", "Contact");} at this point, I believe you have a deeper understanding of "what ASP.NET MVC is". You might as well do it in practice! Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report