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

How to add articles to ASP.NET MVC5 website Development

2025-04-02 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

The main content of this article is "how to add articles to ASP.NET MVC5 website development". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Next let the editor to take you to learn "how to achieve ASP.NET MVC5 website development to add articles"!

First, add articles

1. KindEditor Rich text Editor

Go to the official website http://kindeditor.net/down.php to download the latest version, extract it and copy the code to the project's Scripts folder.

2. Add the display of the interface.

Add an Add method to ArticleController

/ add articles / View page public ActionResult Add () {return View ();}

Right-click to add the strongly typed view of Article, the code is as follows

@ section scripts {/ / edit box KindEditor.ready (function (K) {window.editor = K.create ('# Content', {height: '500px'});}) } @ model Ninesky.Models.Article@using (Html.BeginForm ()) {@ Html.AntiForgeryToken () add articles @ Html.ValidationSummary (true) column @ Html.ValidationMessageFor (model = > model.CommonModel.CategoryID) @ Html.LabelFor (model = > model.CommonModel.Title, new {@ class = "control-label col-sm-2"}) @ Html.TextBoxFor (model = > model.CommonModel.Title) New {@ class = "form-control"}) @ Html.ValidationMessageFor (model = > model.CommonModel.Title) @ Html.LabelFor (model = > model.Author, new {@ class = "control-label col-sm-2"}) @ Html.TextBoxFor (model = > model.Author, new {@ class = "form-control"}) @ Html.ValidationMessageFor (model = > model.Author) @ Html.LabelFor (model = > model.Source New {@ class = "control-label col-sm-2"}) @ Html.TextBoxFor (model = > model.Source, new {@ class = "form-control"}) @ Html.ValidationMessageFor (model = > model.Source) @ Html.LabelFor (model = > model.Intro, new {@ class = "control-label col-sm-2"}) @ Html.TextAreaFor (model = > model.Intro New {@ class = "form-control"}) @ Html.ValidationMessageFor (model = > model.Intro) @ Html.LabelFor (model = > model.Content, new {@ class = "control-label col-sm-2"}) @ Html.EditorFor (model = > model.Content) @ Html.ValidationMessageFor (model = > model.Content) @ Html.LabelFor (model = > model.CommonModel.DefaultPicUrl, new {@ class = "control-label col-sm-2"})

@ Html.HiddenFor (model = > model.CommonModel.DefaultPicUrl) Select … @ Html.ValidationMessageFor (model = > model.CommonModel.DefaultPicUrl)}

The effect is as shown in the picture

3. The processing accepted by the background.

[ValidateInput (false)] [HttpPost] [ValidateAntiForgeryToken] public ActionResult Add (Article article) {if (ModelState.IsValid) {/ / set a 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 doing the architecture, there is an Add method in the base class of DAL and BLL, and we can add it to the database directly using the ArticleService.Add method.

Add the article function to achieve, but can not upload attachments, can not select the home page picture, can not delete redundant attachments. Let's implement the attachment function.

II. Attachment upload

The target can upload attachments (pictures, files, etc.), save the files to the upload directory, and save the corresponding records in the database, you can browse the list of files, and unused attachments can delete records.

I. add attachments

Add the Upload () method in AttachmentController, the method writes the file to disk and saves the attachment record to the database, the middle will be used to read the configuration file, see ".net MVC site configuration file read and write".

/ upload attachment / public ActionResult Upload () {var _ uploadConfig = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration ("~") .GetSection ("UploadConfig") as Ninesky.Models.Config.UploadConfig; / / maximum file limit 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; / / allowed upload type Hashtable extTable = new Hashtable (); extTable.Add ("image", _ uploadConfig.ImageExt); extTable.Add ("flash", _ uploadConfig.FileExt); extTable.Add ("media", _ uploadConfig.MediaExt); extTable.Add ("file", _ uploadConfig.FileExt) / / uploaded file HttpPostedFileBase _ postFile = Request.Files ["imgFile"]; if (_ postFile = = null) return Json (new {error = '1file, message = "Please select a 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 = "file size exceeds the limit"}) / / check the extension if (string.IsNullOrEmpty (_ fileExt) | | Array.IndexOf (string) extTable [_ dirName]). Split (','), _ fileExt.Substring (1). ToLower () =-1) return Json (new {error = 1, message = "uploading files of this type is not allowed. Only the format "+ ((String) extTable [_ dirName]) +" is allowed. " }); _ 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 file _ postFile.SaveAs (_ savePath) / / Save database records 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)});}

Second, query the list of accessories

Open the InterfaceAttachmentService interface, add two methods, both of which are annotated and easy to understand, go directly to the code.

/ find attachment list / Common model ID / / owner / / Type / IQueryable FindList (Nullable modelID, string owner, string type) / find attachment list / Public model ID / / owner / / owner / / contains / IQueryable FindList with ModelID Null (int modelID, string owner, string type,bool withModelIDNull)

Write realistic code in AttachmentService

Public IQueryable FindList (Nullable 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 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;}

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

File View Model in namespace Ninesky.Web.Areas.Member.Models {/ KindEditor File Management / create: 2014.03.09 / 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;}

Add a method FileManagerJson to AttachmentController that returns a list of files. Method is called by the file manager of KindEditor

/ attachment management list / Common model ID / directory (type) / public ActionResult FileManagerJson (int? Id, string dir) {Models.AttachmentManagerViewModel _ attachmentViewModel; IQueryable _ attachments; / / id is null, indicating that the common model id is null. In this case, there is no list of attachments corresponding to the model in the query database (for uploading, but uploaded articles). Not saved yet) if (id = = null) _ attachments = attachmentService.FindList (null, User.Identity.Name, dir); / / id is not null. The specified model id and id are null (newly uploaded) attached with the list else _ attachments = attachmentService.FindList ((int) id, User.Identity.Name, dir, true); / / Loop Construction AttachmentManagerViewModel var _ attachmentList = new List (_ attachments.Count ()) Foreach (var _ attachment in _ attachments) {_ attachmentViewModel = 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 thumbnails for the picture

Write the method of creating thumbnails 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 {/ Picture related / public class Picture {/ create thumbnail address / thumbnail address / width / height / whether public static bool CreateThumbnail (string originalPicture, string thumbnail, int width) is successful or not Int height) {/ / original Image _ original = Image.FromFile (originalPicture) / / RectangleF _ originalArea = new RectangleF (); / / aspect ratio 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); / / set image quality _ graphics.InterpolationMode = InterpolationMode.High; _ graphics.SmoothingMode = SmoothingMode.HighQuality / / draw picture _ 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 action to AttachmentController to generate thumbnails

/ / create thumbnail / original image address / thumbnail address. Failed to generate null public ActionResult CreateThumbnail (string originalPicture) {/ / the original image is a thumbnail and directly returns its address if (originalPicture.IndexOf ("_ s") > 0) return Json (originalPicture); / / the thumbnail address string _ thumbnail = originalPicture.Insert (originalPicture.LastIndexOf ('.'), "_ s") / / create thumbnail if (Common.Picture.CreateThumbnail (Server.MapPath (originalPicture), Server.MapPath (_ thumbnail), 160120)) {/ / record is saved in the database attachmentService.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

Add and upload attachments are done, now integrate them together, we can upload attachments.

Open the Add view and add the script where the KindEditor is created

Now open the browser and you can upload and manage attachments.

The last field to add an article is the default home image of the article. I want to click the Select button to select the picture in the uploaded image and create a thumbnail.

Then a file space pops up in the Add view for the user to select the uploaded file. After the user selects the selected address, the selected address is sent to the server to create the thumbnail, and the thumbnail address is returned, then the address is copied to the hidden form, CommonModel_DefaultPicUrl, and colleagues copy it.

The src property is used to display pictures. The Js code is as follows:

/ / Home 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 thumbnail!") ; else {K ('# CommonModel_DefaultPicUrl') .val (data); K ('# imgpreview') .attr ("src", data);} editor2.hideDialog ();}});}});})

Let's see the effect.

Delete unused attachments in the action where the article is saved

Complete Add method code

[ValidateInput (false)] [HttpPost] [ValidateAntiForgeryToken] public ActionResult Add (Article article) {if (ModelState.IsValid) {/ / set a 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) {/ / attachment processing InterfaceAttachmentService _ attachmentService = new AttachmentService (); / / query related attachments var _ attachments = _ attachmentService.FindList (null, User.Identity.Name, string.Empty). ToList (); / / traverse attachment foreach (var _ att in _ attachments) {var _ filePath = Url.Content (_ att.FileParth) / / if this attachment is used in the picture or content on the front page of the article, change ModelID to the saved ModelID if ((article.CommonModel.DefaultPicUrl! = null & & article.CommonModel.DefaultPicUrl.IndexOf (_ filePath) > = 0) | | article.Content.IndexOf (_ filePath) > 0) {_ att.ModelID = article.ModelID; _ attachmentService.Update (_ att) } / / delete attachments and records in the database else {System.IO.File.Delete (Server.MapPath (_ att.FileParth)); _ attachmentService.Delete (_ att);}} return View ("AddSucess", article);}} return View (article) At this point, I believe that everyone on "how to achieve ASP.NET MVC5 website development to add articles" have a deeper understanding, might as well to the actual operation of it! 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