One, add articles
1. Kindeditor Rich Text Editor
To the official website http://kindeditor.net/down.php Download the latest version, after decompression to copy the code to the project's Scripts folder.
2, add the display of the interface.
Add the Add method in Articlecontroller
<summary>
///Add article
///</summary>
///<returns> View page </returns>
public ActionResult Add ()
{return
View ();
}
Right-click to add a strongly typed view of article with the following code
@section scripts{<script type= "Text/javascript" src= "~/scripts/kindeditor/kindeditor-min.js" ></script > <script type= "Text/javascript" >//edit box Kindeditor.ready (function (K) {window.editor = K.create (' #Conten
T ', {height: ' 500px '});
}); </script>} @model Ninesky.Models.Article @using (Html.BeginForm ()) {@Html. AntiForgeryToken () <div class= "for M-horizontal "role=" form > <h4> add article </h4> <hr/> @Html. ValidationSummary (True) <div class= " Form-group "> <label class=" Control-label col-sm-2 "for=" Commonmodel_categoryid "> Columns </label> <div cl ass= "col-sm-10" > <input id= "Commonmodel_categoryid" name= "Commonmodel.categoryid" URL: ' @ Url.action ("Jsontree", "Category", new {model= "Article"}) ' "Class=" Easyui-combotree "style=" HEIGHT:34PX; width:280px "/> @Html. Validationmessagefor (model => model. Commonmodel.categoryid) </div> </div> <div class= "Form-group "> @Html labelfor (model => model. Commonmodel.title, new {@class = "Control-label col-sm-2"}) <div class= "col-sm-10" > @Html. Textboxfor (model => model. Commonmodel.title, new {@class = "Form-control"}) @Html. validationmessagefor (model => model. Commonmodel.title) </div> </div> <div class= "Form-group" > @Html labelfor (Model => MODEL.A Uthor, new {@class = "Control-label col-sm-2"}) <div class= "col-sm-10" > @Html. Textboxfor (model => model. Author, new {@class = "Form-control"}) @Html. validationmessagefor (model => model. Author) </div> </div> <div class= "Form-group" > @Html. Labelfor (model => model. Source, new {@class = "Control-label col-sm-2"}) <div class= "col-sm-10" > @Html. Textboxfor (Model => model . Source, new {@class = "Form-control"}) @Html. validationmessagefor (model => model. Source) </div> </div> <div class= "Form-group "> @Html labelfor (model => model. Intro, new {@class = "Control-label col-sm-2"}) <div class= "col-sm-10" > @Html. Textareafor (Model => model . Intro, new {@class = "Form-control"}) @Html. validationmessagefor (model => model. Intro) </div> </div> <div class= "Form-group" > @Html. Labelfor (model => model. Content, new {@class = "Control-label col-sm-2"}) <div class= "col-sm-10" > @Html. Editorfor (Model => model . Content) @Html. Validationmessagefor (model => model. Content) </div> </div> <div class= "Form-group" > @Html. Labelfor (model => model. Commonmodel.defaultpicurl, new {@class = "Control-label col-sm-2"}) <div class= "col-sm-10" > <img id= "img Preview "class=" thumbnail "src="/> @Html. Hiddenfor (model => model. Commonmodel.defaultpicurl) <a id= "Btn_picselect" class= "Easyui-linkbutton" > select ...</a> @Html. ValidationMes Sagefor (model => Model. Commonmodel.defaultpicurl) </div> </div> <div class= "Form-group" > <div class= "col-sm-offse T-2 col-sm-10 "> <input type=" Submit "value=" Add "class=" btn btn-default "/> </div> </div> &L
T;/div>}
Effect as shown
3, backstage accept the processing.
[ValidateInput (false)]
[HttpPost]
[Validateantiforgerytoken]
Public ActionResult Add (Article Article)
{
if (modelstate.isvalid)
{
//Set 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 =;
Article = Articleservice.add (article);
if (article. ArticleID > 0)
{return
View ("addsucess", article);
}
return View (article);
}
In the framework of the DAL, BLL base class has the Add method, we can directly use the Articleservice.add method to add to the database
Add the article function is realized, but can not upload attachments, can not select the home page picture, can not delete redundant attachments. The following is the implementation of the attachment function.
Second, attachment upload
Target can upload attachments (pictures, files, etc.), file saved to the upload directory, and the database to save the corresponding records, you can browse the file list, unused attachments can delete records.
One, add accessories
Add the Upload () method in the Attachmentcontroller method to write the file to disk to save the attachment's record in the database, read the configuration file in the middle, see Read and write configuration files in the. Net MVC Web site.
<summary>///upload attachment///</summary>///<returns></returns> public ActionResult Upload ( {var _uploadconfig = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration ("~").
GetSection ("Uploadconfig") as Ninesky.Models.Config.UploadConfig;
File max limit int _maxsize = _uploadconfig.maxsize;
Save path string _savepath;
File path string _fileparth = "~/" + _uploadconfig.path + "/";
filename string _filename;
Extension string _fileext;
File type string _dirname;
The type allowed to 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);
Uploaded files HttpPostedFileBase _postfile = request.files["Imgfile"];
if (_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, ME
ssage = "File size exceeds 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 = "does not allow uploading of this type of file.") \ nthe only "+ ((String) exttable[_dirname]) +" format 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 = U Ser.
Identity.name, uploaddate = DateTime.Now, Type = _dirname});
Return Json (New {error = 0, url = url.content (_fileparth)}); }
second, the query attachment list
Open the Interfaceattachmentservice interface, add two methods, all made comments easier to understand, directly on the code.
<summary>
///Find attachments 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 attachments list
///</summary>
///<param name= "ModelID" > Public model Id</param >
///<param name= "owner" > Owner </param>
///<param name= "type" > owner </param>
///<param name= "Withmodelidnull" > contains modelid null </param>///<returns></returns
>
iqueryable<models.attachment> findlist (int modelid, string owner, String Type,bool withmodelidnull);
Write real-world code in Attachmentservice
Public iqueryable<models.attachment> findlist (nullable<int> modelid, string owner, String type) {var _a
Ttachemts = 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 get a list of JSON format files from the server, write a view model separately for the list format in Ninesky.Web.Areas.Member.Models. Attachmentmanagerviewmodel
Namespace Ninesky.Web.Areas.Member.Models
{
///<summary>
///kindeditor file view model in Files management
///< Remarks>
///creation: 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;}}}
Add a method to return a list of files in Attachmentcontroller Filemanagerjson. Method for Kindeditor File Manager calls
<summary>///Attachment management list///</summary>///<param name= "IDs" > Public models id</param>///<param Name= "dir" > directory (Type) </param>///<returns></returns> public actionresult filemanagerjson (int? ID, s
Tring dir) {Models.attachmentmanagerviewmodel _attachmentviewmodel;
Iqueryable<attachment> _attachments; The ID is null, indicating that the public model ID is NULL, and there is no list of attachments to the model in the query database (above, but the uploaded article ...).
Not yet saved) if (id = = NULL) _attachments = Attachmentservice.findlist (null, User.Identity.Name, dir); ID is not NULL, return the specified model ID and ID null (newly uploaded) attachment list Else _attachments = attachmentservice.findlist (int) ID, User.Identity.Name,
Dir, True); Cyclic construction attachmentmanagerviewmodel var _attachmentlist = new List<models.attachmentmanagerviewmodel> (_ Attachments.
Count ()); foreach (Var _attachment in _attachments) {_attachmentviewmodel = new Models.attachmentmanagerviewmodel () {Datetim E = _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 pictures
The method of creating thumbnails is written in the common project
Add a method to the Ninesky.common picture class
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>///pictures related///<remarks>///create: 2014.02.11///</remarks>/ </summary> public class Picture {///<summary>///create thumbnails///</summary>///<param Name = "Originalpicture" > Original address </param>///<param name= "thumbnail" > Thumbnail address </param>///<param name= " Width "> Width </param>///<param name=" height "> High </param>///<returns> Success </returns> Pub LIC static bool Createthumbnail (string originalpicture, string thumbnail, int width, int height) {//original Image _ori
ginal = Image.FromFile (originalpicture);
The original artwork uses the area RectangleF _originalarea = new RectangleF ();
Width-height 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 picture quality _graphics.
Interpolationmode = Interpolationmode.high; _graphics.
SmoothingMode = smoothingmode.highquality; Draw a 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 an action that generates thumbnails in Attachmentcontroller
<summary>
///Create thumbnails
///</summary>
///<param name= "Originalpicture" > Original address </ param>
///<returns> thumbnail address. Build failure returns null</returns> public
ActionResult createthumbnail (string originalpicture)
{
// The artwork returns the thumbnail directly to its address
if (Originalpicture.indexof ("_s") > 0) return Json (originalpicture);
Thumbnail address
string _thumbnail = Originalpicture.insert (Originalpicture.lastindexof ('. '), "_s");
Create thumbnails
if (Common.Picture.CreateThumbnail Server.MapPath (originalpicture), Server.MapPath (_thumbnail), 160, )
{
//records are 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);
}
Third, integration
Add and upload attachments are done, now integrate them together, we can upload the attachment.
Open the Add view and add the script at the creation Kindeditor location
Now you can upload and manage attachments by opening your browser
Add the last field of the article is the default home page picture, I would like to click on the selection button, you can upload a picture, and create thumbnails.
Then pop up a file space in Add view to let the user select the uploaded file, the user chooses the address to send to the server to create thumbnails, and return the thumbnail address, and then copy the address to the hidden form, Commonmodel_defaultpicurl, colleagues copy < The SRC attribute of the img/> is used to display pictures. The JS code is as follows:
Homepage picture
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 ();}});});
Look at the effect.
Remove unused attachments from the action that saves the article
The complete Add method code
[ValidateInput (False)]
[HttpPost] [Validateantiforgerytoken] public actionresult Add (Article Article) {if (modelstate.isvalid) {//Set fixed value a Rticle.
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); This attachment is used in the first picture or content of the article to change the ModelID if (article) after the modelid is saved for the article. Commonmodel.defaultpicurl!= null && article. CommonModel.DefaultPicUrl.IndexOf (_filepath) >= 0) | | Article. Content.indexof (_filepath) > 0) {_att. ModelID = article.
ModelID;
_attachmentservice.update (_att); ///No use of the modified attachment deletes the attachment and the records in the database else {System.IO.File.Delete Server.MapPath (_att.
Fileparth));
_attachmentservice.delete (_att);
} return View ("addsucess", article);
} return View (article); }
Simply adding articles is simpler and more complex in uploading attachments, browsing newly added attachments, deleting unused attachments from articles, and generating thumbnails. Kindeditor also support the bulk upload attachment, due to the use of bulk upload swfupload, in the submission of Flash did not transmit cookies to the server, can not verify the user caused upload failed, temporarily unable to use bulk upload, I hope this article can be helpful to everyone's study, We can combine small series of articles before the study, I believe there will be some gains.