Last did the display of the list of articles, and then realize the modification and deletion of the article this part of the end, the content is relatively simple, because has done to add articles, modify the article very similar, is more than a tryupdatemodel part of the update model data.
First, delete the article
Because the public model is associated with, the article, the attachment, so the deletion order here is very important, if you delete the model first, then the article modelid and the attachment of the modelid will become null, so first delete the article and attachment and then delete the public model.
Since the public model and attachment are one-to-many relationships, we have to delete the public model and delete the attachment to write together.
There is a default delete method in the Baserepository class of BLL, but only the model is deleted in this method and the foreign key is not deleted, so the default method is in the commonmodelrepository at the new one.
Public new bool Delete (Models.commonmodel Commonmodel, bool Issave = True)
{
if (commonmodel.attachment!= null) n Context.Attachments.RemoveRange (commonmodel.attachment);
NContext.CommonModels.Remove (Commonmodel);
Return Issave? Ncontext.savechanges () > 0:true;
}
This means to seal off the inherited Delete method, delete the attachment, and then delete the public model in the new method if there is an append. So what if we want to call the base class's Delete method? You can use base. Delete.
OK, now it's time to start deleting.
Add the Delete method in Articlecontroller
<summary>
///Delete
///</summary>
///<param name= "id" > Article id</param>
/// <returns></returns> Public
jsonresult Delete (int id)
{
//delete attachment
var _article = Articleservice.find (ID);
if (_article = null) return Json (false);
Attachment list
var _attachmentlist = _article.commonmodel.attachment;
var _commonmodel = _article.commonmodel;
Delete Article
if (Articleservice.delete (_article))
{
//delete attachment file
foreach (Var _attachment in _ Attachmentlist)
{
System.IO.File.Delete (Server.MapPath) (_attachment. Fileparth));
}
Delete the public model
Commonmodelservice.delete (_commonmodel);
Return Json (TRUE);
}
else return Json (false);
Second, modify the article
This section is very similar to adding articles
First, add edit to display the editing view in Articlecontroller
<summary>
///Modify
///</summary>
///<param name= "id" ></param>
///< returns></returns> public
actionresult Edit (int id)
{return
View (Articleservice.find (ID));
}
Right-click to add a view, this is similar to add, there is nothing to say directly on the 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 ', Uploadjson: ' @Url. Action ("Upload", "attachment") ', Filemanagerjson: ' @Url. Action ("Filem Anagerjson "," attachment ", new {id = @Model. commonmodel.modelid}) ', Allowfilemanager:true, Formatuploadurl:fal
SE}); Homepage picture var Editor2 = K.editor ({filemanagerjson: ' @Url. Action ("Filemanagerjson", "attachment", new {id= @Model. Commo
Nmodel.modelid}) "}); K (' #btn_picselect '). Click (function () {editor2.loadplugin (' filemanager '), function () {Editor2.plugin.filemanage
Rdialog ({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 ();
}
});
}
});
});
});
}); </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 "Value=" @Model. Commonmodel.categoryid "/> @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 (Mode L => model. Commonmodel.title, new {@class = "Form-control"}) @Html. validationmessagefor (model => model. Commonmodel.title) </div> </div> <div class= "Form-group" > @Html. Labelfor (model => model. Author, 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=" @Model. Commonmodel.defaultpicurl "/> @Html. Hiddenfor (model => model. CommonModel.defaultpicurl) <a id= "Btn_picselect" class= "Easyui-linkbutton" > select ...</a> @Html. ValidationMessageFo R (model => model. Commonmodel.defaultpicurl) </div> </div> <div class= "Form-group" > <div class= "col-sm-offse T-2 col-sm-10 "> <input type=" Submit "value=" Save "class=" btn btn-default "/> </div> </div> &L
T;/div>}
The
starts to do background acceptance code and adds the following code to the Articlecontroller.
[HttpPost]
[ValidateInput (False)] [Validateantiforgerytoken] public ActionResult Edit () {int _id = Int.
Parse (ControllerContext.RouteData.GetRequiredString ("id"));
var Article = Articleservice.find (_id);
TryUpdateModel (article, new string[] {"Author", "Source", "Intro", "Content"}); TryUpdateModel (article.
Commonmodel, "Commonmodel", new string[] {"CategoryID", "Title", "Defaultpicurl"}); if (modelstate.isvalid) {if (Articleservice.update (article)) {//Attachment processing Interfaceattachmentservice _att
Achmentservice = new Attachmentservice (); var _attachments = _attachmentservice.findlist (article. Commonmodel.modelid, User.Identity.Name, String. Empty,true).
ToList (); foreach (Var _att in _attachments) {var _filepath = url.content (_att.
Fileparth); if (article. Commonmodel.defaultpicurl!= null && article. CommonModel.DefaultPicUrl.IndexOf (_filepath) >= 0) | | Article. Content.indexof (_filepath) > 0) {_aTt. ModelID = article.
ModelID;
_attachmentservice.update (_att); else {System.IO.File.Delete Server.MapPath (_att.
Fileparth));
_attachmentservice.delete (_att);
} return View ("editsucess", article);
} return View (article);
}
Explain it in detail:
1, [ValidateInput (false)] means that the input is not validated. Because the article content contains HTML code to prevent commit failure.
2, [Validateantiforgerytoken] is to prevent the forgery of cross-station requests, it is said that only the real request to pass.
See the Red Line section of the diagram, construct the validation string in an attempt, and then verify it in the background.
3, public ActionResult Edit (). Seeing that this method does not receive any data, we use the TryUpdateModel update model in the method. Because the user can not be completely trusted, for example, if the user constructs a categgoryid come over, will publish the article to other columns.
This is to get the ID parameter in the route
Look at these two lines, slightly different.
The first line updates the article model directly. The first parameter is the model to be updated, and the second parameter is the updated field.
The second line is slightly different, adding a prefix parameter, we see the view generated code @Html. Textboxfor (model => Model.CommonModel.Title is prefixed with Commonmodel. So here you have to use a prefix to update the view.
Iii. Modify the list of articles
After you finish writing the article, change the article List code to delete and modify the article.
Open the list view and modify the section by 2.
1, JS script part
<script type= "Text/javascript" > $ ("#article_list"). DataGrid ({loadmsg: ' Loading ... ', pagination:true, url: ' @Url. Action ("Jsonlist", "Article") ', columns: [[{field: ' ModelID ', title: ' ID ', checkbox:true}, {field: ' Categoryna Me ', Title: ' Column '}, {field: ' title ', Title: ' Caption '}, {field: ' Inputer ', title: ' Input ', align: ' right '}, {field: ' H Its ', Title: ' Click ', align: ' right '}, {field: ' ReleaseDate ', title: ' Release Date ', align: ' right ', formatter:function (value,
Row, index) {return Jsondateformat (value);}, {field: ' Statusstring ', title: ' State ', width:100, align: ' right '} ], toolbar: ' #toolbar ', IDfield: ' ModelID ', ondblclickrow:function (RowIndex, RowData) {Window.parent.addTab ("modified Chapter "," @Url. Action ("Edit", "Article")/"+ Rowdata.modelid," icon-page ");
}
});
Look for $ ("#btn_search"). Click (function () {$ ("#article_list"). DataGrid (' Load ', {title: $ ("#textbox_title"). Val (), Input: $ ("#textbox_inputer"). Val (), Category: $ ("#combo_category"). Combotree (' GetValue '), FromDate: $ (" #datebox_fromdate "). Datebox (' GetValue '), ToDate: $ (" #datebox_todate ").
Datebox (' GetValue ')});
});
Modify Event function Eidt () {var rows = $ ("#article_list"). DataGrid ("Getselections");
if (!rows | | Rows.length < 1) {$.messager.alert ("hint", "Please select the line to modify!");
Return
else if (rows.length!= 1) {$.messager.alert ("hint", "can only select one row!");
Return else {Window.parent.addTab ("Modify article", "@Url. Action" ("Edit", "Article")/"+ rows[0].
ModelID, "Icon-page");
}//Remove function del () {var rows = $ ("#article_list"). DataGrid ("Getselections");
if (!rows | | Rows.length < 1) {$.messager.alert ("hint", "No row selected!");
Return else if (Rows.length > 0) {$.messager.confirm ("Confirm", "Are you sure you want to delete the selected row?)
", function (r) {if (R) {$.messager.progress ();
$.each (rows, function (index, value) {$.ajax ({type: Post), url: "@Url. Action (" Delete "," Article ")", Data: {Id:value.
ModelID},Async:false, Success:function (data) {}});
});
$.messager.progress (' close ');
Clear Select row Rows.length = 0;
$ ("#article_list"). DataGrid (' reload ');
}
});
Return
}} </script>
Added Modify method, delete method, add row in DataGrid Double click to change the View method
Ondblclickrow:function (RowIndex, RowData) {Window.parent.addTab ("Modify article", "@Url. Action (" Edit "," Article ")/" + Rowdata.modelid, "Icon-page"); }
2,
Iv. my list of articles
My article list is similar to all the articles, and simplifies the part of the content, simpler, and directly on the code.
Add in article Controller
<summary>///article List json "pay attention to permissions issues, can ordinary people access?"
"///</summary>///<param name=" title "> title </param>///<param name=" input "> Entry </param> <param name= "category" > Column </param>///<param name= "FromDate" > Date </param>///<param Name= "ToDate" > Date stop </param>///<param name= "pageIndex" > Page </param>///<param name= "PageSize" & gt; per-page Records </param>///<returns></returns> public actionresult jsonlist (string title, string input, Nul lable<int> category, Nullable<datetime> fromdate, nullable<datetime> toDate, int pageIndex = 1, int pag
Esize = = {if (category = = null) Category = 0;
int _total; var _rows = commonmodelservice.findpagelist (out of _total, PageIndex, PageSize, "Article", title, (int) category, input, from Date, ToDate, 0). Select (cm => new Ninesky.Web.Models.CommonModelViewModel () {CategoryID = cm. CategoryID, CategoryName =Cm. Category.name, Defaultpicurl = cm. Defaultpicurl, Hits = cm. Hits, inputer = cm. Inputer, Model = cm. Model, modelid = cm. ModelID, releasedate = cm. ReleaseDate, Status = cm. Status, Title = cm.
Title}); Return Json (New {total = _total, rows = _rows.
ToList ()});
Public ActionResult MyList () {return View (); ///<summary>///My articles list///</summary>///<param name= "title" ></param>///<para M name= "FromDate" ></param>///<param name= "toDate" ></param>///<param-name= "PageIndex" >& lt;/param>///<param name= "pageSize" ></param>///<returns></returns> public Actionresul T Myjsonlist (string title, Nullable<datetime> fromdate, nullable<datetime> toDate, int pageIndex = 1, int page
Size =) {int _total; var _rows = commonmodelservice.findpagelist (out _total, PageIndex, PageSize, "Article", title, 0, String. Empty, FromDate, ToDate, 0). Select (cm => new Ninesky.Web.Models.CommonModelViewModel () {CategoryID = cm. CategoryID, CategoryName = cm. Category.name, Defaultpicurl = cm. Defaultpicurl, Hits = cm. Hits, inputer = cm. Inputer, Model = cm. Model, modelid = cm. ModelID, releasedate = cm. ReleaseDate, Status = cm. Status, Title = cm.
Title}); Return Json (New {total = _total, rows = _rows.
ToList ()}, Jsonrequestbehavior.allowget); Add a view for mylist <div id= "Toolbar" > <div> <a href= "#" class= "Easyui-linkbutton" data-options= "iconcls: ' I Con-edit ', plain:true "onclick=" Eidt () "> Modify </a> <a href=" # "class=" Easyui-linkbutton "data-options=" Iconcls: ' Icon-remove ', Plain:true ' onclick= "del ()" > Delete </a> <a href= "#" class= "Easyui-linkbutton" data-options= "Iconcls: ' Icon-reload ', plain:true" onclick= "$ (' #article_list '). DataGrid (' reload '); > Refresh </a> </div> <div class= "Form-inline" > <label> title </label> <input id= "Textbox_title" class= "Input-easyui" style= "width:280px"/> <label> Add date </label> <input id= "datebox_fromdate" type= "datetime" class= "Easyui-datebox" style= "width:120px"/>-< Input id= "datebox_todate" type= "datetime" class= "Easyui-datebox" style= "width:120px"; "/> <a href=" # "id=" Btn_search "data-options=" iconcls: ' Icon-search ' "class=" Easyui-linkbutton "> Query </a > </div> </div> <table id= "article_list" ></table> <script src= "~/scripts/common.js" ></script> <script type= "Text/javascript" > $ ("#article_list"). DataGrid ({loadmsg: ' Loading ... ', pagination
: True, url: ' @Url. Action ("Myjsonlist", "Article") ', columns: [[{field: ' ModelID ', title: ' ID ', checkbox:true}, {field: ' CategoryName ', title: ' Columns '}, {field: ' title ', Title: ' Caption '}, {field: ' Inputer ', title: ' Input ', align: ' r Ight '}, {field: ' Hits ', title: ' Click ', align: ' right '}, {field: ' ReleasedAte ', Title: ' Release Date ', align: ' right ', formatter:function (value, row, index) {return Jsondateformat (value);}}, {Fie LD: ' statusstring ', title: ' State ', width:100, align: ' right '}], toolbar: ' #toolbar ', IDfield: ' ModelID ', ONDBLCL Ickrow:function (RowIndex, RowData) {Window.parent.addTab ("Modify article," @Url. Action ("Edit", "Article")/"+ Rowdata.modelid , "Icon-page");
}
});
Look for $ ("#btn_search"). Click (function () {$ ("#article_list"). DataGrid (' Load ', {title: $ ("#textbox_title"). Val (),
FromDate: $ ("#datebox_fromdate"). Datebox (' GetValue '), ToDate: $ ("#datebox_todate"). Datebox (' GetValue ')});
});
Modify Event function Eidt () {var rows = $ ("#article_list"). DataGrid ("Getselections");
if (!rows | | Rows.length < 1) {$.messager.alert ("hint", "Please select the line to modify!");
Return
else if (rows.length!= 1) {$.messager.alert ("hint", "can only select one row!");
Return else {Window.parent.addTab ("Modify article", "@Url. Action" ("Edit", "Article")/"+ rows[0].
ModelID, "Icon-page");
} }//delete function del () {var rows = $ ("#article_list"). DataGrid ("Getselections");
if (!rows | | Rows.length < 1) {$.messager.alert ("hint", "No row selected!");
Return else if (Rows.length > 0) {$.messager.confirm ("Confirm", "Are you sure you want to delete the selected row?)
", function (r) {if (R) {$.messager.progress ();
$.each (rows, function (index, value) {$.ajax ({type: Post), url: "@Url. Action (" Delete "," Article ")", Data: {Id:value.
ModelID}, Async:false, Success:function (data) {}});
});
$.messager.progress (' close ');
Clear Select row Rows.length = 0;
$ ("#article_list"). DataGrid (' reload ');
}
});
Return }} </script>
The
Should note is deletes the article the order which deletes, changes the article when the TryUpdateModel use, hoped this article to everybody's study to be helpful.