ASP. NET MVC5 website development add article (8), mvc5 website development

Source: Internet
Author: User

ASP. NET MVC5 website development add article (8), mvc5 website development

I. add an article
1. KindEditor Rich Text Editor

Go to the official website http://kindeditor.net/down.php to download the latest version, decompress it, and copy the code to the scriptsfolder of the project.

2. display the page.

Add the Add method to ArticleController

/// <Summary> /// Add an article /// </summary> /// <returns> View page </returns> public ActionResult Add () {return View ();}

Right-click to add the Article strong view. The Code is as follows:

@ Section scripts {<script type = "text/javascript" src = "~ /Scripts/KindEditor/kindeditor-min.js "> </script> <script type =" text/javascript "> // edit the box KindEditor. ready (function (K) {window. editor = K. create ('# content', {height: '500px'}) ;}); </script >}@ model Ninesky. models. article @ using (Html. beginForm () {@ Html. antiForgeryToken () <div class = "form-horizontal" role = "form"> 


Effect

3. Processing accepted by the background.

[ValidateInput (false)] [HttpPost] [ValidateAntiForgeryToken] public ActionResult Add (Article article) {if (ModelState. isValid) {// set the fixed value article. commonModel. hits = 0; article. commonModel. inputer = User. identity. name; article. commonModel. model = "Article"; article. commonModel. releaseDate = System. dateTime. now; article. commonModel. status = 99; article = articleService. add (article); if (article. articleID> 0) {return View ("AddSucess", article) ;}} return View (article );}


When constructing the architecture, the DAL and BLL base classes have the Add method. We can directly use the ArticleService. Add method to Add the method to the database.

You can add an article, but you cannot upload attachments, select a homepage image, or delete unnecessary attachments. The following describes how to implement the attachment function.

Ii. Attachment upload
The target can upload attachments (images, files, etc.), save the files to the upload directory, and save the corresponding records in the database. You can browse the file list, and delete unused attachments.

I. Add attachments

Add the Upload () method to AttachmentController to write files to the disk and save the attachment records to the database. Read the configuration file in the middle. See 《.. Net MVC website configuration file read/write.

/// <Summary> /// Upload the attachment /// </summary> /// <returns> </returns> public ActionResult Upload () {var _ uploadConfig = System. web. configuration. webConfigurationManager. openWebConfiguration ("~ "). GetSection ("UploadConfig") as Ninesky. models. config. uploadConfig; // maximum file size: int _ maxSize = _ uploadConfig. maxSize; // save path string _ savePath; // file path string _ fileParth = "~ /"+ _ UploadConfig. path + "/"; // file name string _ fileName; // extension string _ fileExt; // file type string _ dirName; // The type that can be uploaded. Hashtable extTable = new Hashtable (); extTable. add ("image", _ uploadConfig. imageExt); extTable. add ("flash", _ uploadConfig. fileExt); extTable. add ("media", _ uploadConfig. mediaExt); extTable. add ("file", _ uploadConfig. fileExt); // the uploaded file HttpPostedFileBase _ postFile = Request. files ["imgFile"]; I F (_ postFile = null) return Json (new {error = '1', message = "select file"}); _ fileName = _ postFile. fileName; _ fileExt = Path. getExtension (_ fileName ). toLower (); // file type _ dirName = Request. queryString ["dir"]; if (string. isNullOrEmpty (_ dirName) {_ dirName = "image";} if (! ExtTable. containsKey (_ dirName) return Json (new {error = 1, message = "directory type does not exist"}); // file size if (_ postFile. inputStream = null | _ postFile. inputStream. length> _ maxSize) return Json (new {error = 1, message = "the file size exceeds the limit"}); // check if (string. isNullOrEmpty (_ fileExt) | Array. indexOf (string) extTable [_ dirName]). split (','), _ fileExt. substring (1 ). toLower () =-1) return Json (new {error = 1, message = "This type of file cannot be uploaded. \ N only supports the "+ (String) extTable [_ dirName]) +" format. "}); _ FileParth + = _ dirName +"/"+ DateTime. now. toString ("yyyy-MM") + "/"; _ savePath = Server. mapPath (_ fileParth); // check the upload directory if (! Directory. exists (_ savePath) Directory. createDirectory (_ savePath); string _ newFileName = DateTime. now. toString ("yyyyMMdd_hhmmss") + _ fileExt; _ savePath + = _ newFileName; _ fileParth + = _ newFileName; // save the file _ postFile. saveAs (_ savePath); // Save the database record attachmentService. add (new Attachment () {Extension = _ fileExt. substring (1), FileParth = _ fileParth, Owner = User. identity. name, UploadDate = DateTime. now, Type = _ dirName}); return Json (new {error = 0, url = Url. content (_ fileParth )});}


Ii. query the Attachment List

Open the InterfaceAttachmentService interface and add two methods. The comments are easy to understand and the code is directly added.

/// <Summary> /// find the Attachment List /// </summary> /// <param name = "modelID"> Public Model ID </param> /// <param name = "owner"> owner </param> /// <param name = "type"> type </param> /// <returns> </returns> IQueryable <Models. attachment> FindList (Nullable <int> modelID, string owner, string type ); /// <summary> /// find the Attachment List /// </summary> /// <param name = "modelID"> Public Model ID </param> /// <param name = "owner"> owner </param> /// <param name = "type"> owner </param> /// <param name = "withModelIDNull"> </param> /// <returns> </returns> IQueryable <Models. attachment> FindList (int modelID, string owner, string type, bool withModelIDNull );

Write real code in AttachmentService

public IQueryable<Models.Attachment> FindList(Nullable<int> modelID, string owner, string type)  {   var _attachemts = CurrentRepository.Entities.Where(a => a.ModelID == modelID);   if (!string.IsNullOrEmpty(owner)) _attachemts = _attachemts.Where(a => a.Owner == owner);   if (!string.IsNullOrEmpty(type)) _attachemts = _attachemts.Where(a => a.Type == type);   return _attachemts;  }  public IQueryable<Models.Attachment> FindList(int modelID, string owner, string type, bool withModelIDNull)  {   var _attachemts = CurrentRepository.Entities;   if (withModelIDNull) _attachemts = _attachemts.Where(a => a.ModelID == modelID || a.ModelID == null);   else _attachemts = _attachemts.Where(a => a.ModelID == modelID);   if (!string.IsNullOrEmpty(owner)) _attachemts = _attachemts.Where(a => a.Owner == owner);   if (!string.IsNullOrEmpty(type)) _attachemts = _attachemts.Where(a => a.Type == type);   return _attachemts;  }

Because KindEditor file management needs to obtain the list of json files from the server, write a view model for the List format separately in Ninesky. Web. Areas. Member. Models. AttachmentManagerViewModel

Namespace Ninesky. web. areas. member. models {/// <summary> /// File View model in KindEditor file management /// <remarks> /// create: 2014.03.09 // </remarks> /// </summary> public class AttachmentManagerViewModel {public bool is_dir {get; set;} public bool has_file {get; set ;} public int filesize {get; set;} public bool is_photo {get; set;} public string filetype {get; set;} public string filename {get; set ;} public string datetime {get; set ;}}}

In AttachmentController, add the FileManagerJson method to return the file list. Method called by KindEditor's file manager

/// <Summary> /// attachment management list /// </summary> /// <param name = "id"> Public Model ID </param> /// <param name = "dir"> directory (type) </param> /// <returns> </returns> public ActionResult FileManagerJson (int? Id, string dir) {Models. attachmentManagerViewModel _ attachmentViewModel; IQueryable <Attachment> _ attachments; // The id is null, indicating that the public model id is null, at this time, the list of attachments in the database that do not match the model is queried (the uploaded articles are uploaded ...... Not saved) if (id = null) _ attachments = attachmentService. findList (null, User. identity. name, dir); // If the id is not null, the system returns the list of else _ attachments = attachmentService with the specified model id and id being null (newly uploaded. findList (int) id, User. identity. name, dir, true); // cyclically constructs AttachmentManagerViewModel var _ attachmentList = new List <Models. attachmentManagerViewModel> (_ attachments. count (); foreach (var _ attachment in _ attachments) {_ attachmentVi EwModel = new Models. attachmentManagerViewModel () {datetime = _ attachment. uploadDate. toString ("yyyy-MM-dd HH: mm: ss"), filetype = _ attachment. extension, has_file = false, is_dir = false, is_photo = _ attachment. type. toLower () = "image "? True: false, filename = Url. content (_ attachment. fileParth)}; FileInfo _ fileInfo = new FileInfo (Server. mapPath (_ attachment. fileParth); _ attachmentViewModel. filesize = (int) _ fileInfo. length; _ attachmentList. add (_ attachmentViewModel);} return Json (new {moveup_dir_path = "", current_dir_path = "", current_url = "", total_count = _ attachmentList. count, file_list = _ attachmentList}, JsonRequestBehavior. allowGet );}

3. Create a thumbnail for the image

Write the method for creating a thumbnail in the Common project.

Add a method to the Picture class of Ninesky. Common

Using System; using System. collections. generic; using System. linq; using System. text; using System. threading. tasks; using System. drawing; using System. drawing. drawing2D; using System. security. cryptography; namespace Ninesky. common {/// <summary> /// image related /// <remarks> /// create: /// </remarks> /// </summary> public class Picture {// <summary> /// create a thumbnail /// </summary> /// <param name = "originalPicture"> source image address </param> /// <param name = "thumbnail"> thumbnail address </param> /// <param name = "width "> width </param> /// <param name =" height "> height </param> /// <returns> whether the request is successful </returns> public static bool CreateThumbnail (string originalPicture, string thumbnail, int width, int height) {// source Image _ original = Image. fromFile (originalPicture); // use the region RectangleF _ originalArea = new RectangleF (); // float _ ratio = (float) width/height; if (_ ratio> (float) _ original. width/_ original. height) {_ originalArea. X = 0; _ originalArea. width = _ original. width; _ originalArea. height = _ originalArea. width/_ ratio; _ originalArea. Y = (_ original. height-_ originalArea. height)/2;} else {_ originalArea. Y = 0; _ originalArea. height = _ original. height; _ originalArea. width = _ originalArea. height * _ ratio; _ originalArea. X = (_ original. width-_ originalArea. width)/2;} Bitmap _ bitmap = new Bitmap (width, height); Graphics _ graphics = Graphics. fromImage (_ bitmap); // sets image quality _ graphics. interpolationMode = InterpolationMode. high; _ graphics. smoothingMode = SmoothingMode. highQuality; // draw image _ graphics. clear (Color. transparent); _ graphics. drawImage (_ original, new RectangleF (0, 0, _ bitmap. width, _ bitmap. height), _ originalArea, GraphicsUnit. pixel); // save _ bitmap. save (thumbnail); _ graphics. dispose (); _ original. dispose (); _ bitmap. dispose (); return true ;}}}

Add an action to generate a thumbnail in AttachmentController

/// <Summary> /// create a thumbnail /// </summary> /// <param name = "originalPicture"> source image address </param> /// <returns> thumbnail address. If the generation fails, null is returned. </returns> public ActionResult CreateThumbnail (string originalPicture) {// if the source image is a thumbnail, its address if (originalPicture. indexOf ("_ s")> 0) return Json (originalPicture); // The thumbnail address string _ thumbnail = originalPicture. insert (originalPicture. lastIndexOf ('. '), "_ s"); // create a thumbnail if (Common. picture. createThumbnail (Server. mapPath (originalPicture), Server. mapPath (_ thumbnail), 160,120) {// record stored in the database attachmentSe Rvice. Add (new Attachment () {Extension = _ thumbnail. Substring (_ thumbnail. LastIndexOf ('.') + 1), FileParth = "~ "+ _ Thumbnail, Owner = User. identity. name, Type = "image", UploadDate = DateTime. now}); return Json (_ thumbnail);} return Json (null );}


Iii. Integration
After adding and uploading attachments, we can upload them together.

Open the Add view and Add a script at the position where KindEditor is created.

Now you can open your browser to upload and manage attachments.

The last field for adding an article is the default homepage image of the article. I want to click the select button to select an image from the uploaded file and create a thumbnail.

In the Add view, a file space pops up to allow the user to select the uploaded file. After the user selects the file, the selected address is sent to the server to create a thumbnail and the thumbnail address is returned, copy the address to the hidden form, commonmodel_defapicpicurl, and copy the src attribute to display the image. The Js Code is as follows:

// Homepage image var editor2 = K. editor ({fileManagerJson: '@ Url. action ("FileManagerJson", "Attachment") '}); K (' # btn_picselect '). click (function () {editor2.loadPlugin ('filemanager', function () {editor2.plugin. filemanagerDialog ({viewType: 'view', dirName: 'image', clickFn: function (url, title) {var url; $. ajax ({type: "post", url: "@ Url. action ("CreateThumbnail", "Attachment") ", data: {originalPicture: Url}, async: false, success: function (data) {if (data = null) alert ("failed to generate a thumbnail! "); Else {K ('# commonmodel_defapicpicurl '). val (data); K ('# imgpreview '). attr ("src", data) ;}editor2.hidedialog ();}});}});});});


View the effect

Delete unused attachments in the action of saving the document

Complete Add method code

[ValidateInput (false)] [HttpPost] [ValidateAntiForgeryToken] public ActionResult Add (Article article) {if (ModelState. isValid) {// set the fixed value article. commonModel. hits = 0; article. commonModel. inputer = User. identity. name; article. commonModel. model = "Article"; article. commonModel. releaseDate = System. dateTime. now; article. commonModel. status = 99; article = articleService. add (article); if (article. articl EID> 0) {// InterfaceAttachmentService _ attachmentService = new AttachmentService (); // query the relevant Attachment var _ attachments = _ attachmentService. findList (null, User. identity. name, string. empty ). toList (); // traverse the attachment foreach (var _ att in _ attachments) {var _ filePath = Url. content (_ att. fileParth); // if this attachment is used in the image or content on the homepage of the document, change the ModelID to the saved ModelID if (article. commonModel. defapicpicurl! = Null & article. commonModel. defapicpicurl. indexOf (_ filePath)> = 0) | article. content. indexOf (_ filePath)> 0) {_ att. modelID = article. modelID; _ attachmentService. update (_ att);} // Delete the attachment and record else {System. IO. file. delete (Server. mapPath (_ att. fileParth); _ attachmentService. delete (_ att) ;}} return View ("AddSucess", article) ;}} return View (article );}

Simply adding an article is relatively simple. The complex points are uploading attachments, browsing newly added attachments, deleting unused attachments in the article, and generating thumbnails. KindEditor also supports batch upload of attachments. Because swfupload is used for batch upload, flash does not transmit cookies to the server during submission, and users cannot be verified, causing upload failure, I hope this article will be helpful to everyone's learning. You can combine the articles published earlier in the small series to learn from them. I believe they will surely reap some gains.

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.