asp.net MVC5 website Development Modification and deletion article (10) _ Practical skills

Source: Internet
Author: User
Tags datetime

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{&lt;script type= "Text/javascript" src= "~/scripts/kindeditor/kindeditor-min.js" &gt;&lt;/script &gt; &lt;script type= "Text/javascript" &gt;//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 ();
      }
       });
    }
     });
   });
  });
 }); &lt;/script&gt;} @model Ninesky.Models.Article @using (Html.BeginForm ()) {@Html. AntiForgeryToken () &lt;div class= "for M-horizontal "role=" form &gt; &lt;h4&gt; add article &lt;/h4&gt; &lt;hr/&gt; @Html. ValidationSummary (True) &lt;div class= " Form-group "&gt; &lt;label class=" Control-label col-sm-2 "for=" Commonmodel_categoryid "&gt; Columns &lt;/label&gt; &lt;div cl ass= "col-sm-10" &gt; &lt;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 "/&gt; @Html. ValidatiOnmessagefor (model =&gt; model. Commonmodel.categoryid) &lt;/div&gt; &lt;/div&gt; &lt;div class= "Form-group" &gt; @Html. Labelfor (model =&gt; model. Commonmodel.title, new {@class = "Control-label col-sm-2"}) &lt;div class= "col-sm-10" &gt; @Html. Textboxfor (Mode L =&gt; model. Commonmodel.title, new {@class = "Form-control"}) @Html. validationmessagefor (model =&gt; model. Commonmodel.title) &lt;/div&gt; &lt;/div&gt; &lt;div class= "Form-group" &gt; @Html. Labelfor (model =&gt; model. Author, new {@class = "Control-label col-sm-2"}) &lt;div class= "col-sm-10" &gt; @Html. Textboxfor (Model =&gt; model . Author, new {@class = "Form-control"}) @Html. validationmessagefor (model =&gt; model. Author) &lt;/div&gt; &lt;/div&gt; &lt;div class= "Form-group" &gt; @Html. Labelfor (model =&gt; model. Source, new {@class = "Control-label col-sm-2"}) &lt;div class= "col-sm-10" &gt; @Html. Textboxfor (Model =&gt; model . Source, new {@class = "Form-control"}) @Html. Validationmessagefor (model =&gt; model. Source) &lt;/div&gt; &lt;/div&gt; &lt;div class= "Form-group" &gt; @Html. Labelfor (model =&gt; model. Intro, new {@class = "Control-label col-sm-2"}) &lt;div class= "col-sm-10" &gt; @Html. Textareafor (Model =&gt; model . Intro, new {@class = "Form-control"}) @Html. validationmessagefor (model =&gt; model. Intro) &lt;/div&gt; &lt;/div&gt; &lt;div class= "Form-group" &gt; @Html. Labelfor (model =&gt; model. Content, new {@class = "Control-label col-sm-2"}) &lt;div class= "col-sm-10" &gt; @Html. Editorfor (Model =&gt; model . Content) @Html. Validationmessagefor (model =&gt; model. Content) &lt;/div&gt; &lt;/div&gt; &lt;div class= "Form-group" &gt; @Html. Labelfor (model =&gt; model. Commonmodel.defaultpicurl, new {@class = "Control-label col-sm-2"}) &lt;div class= "col-sm-10" &gt; &lt;img id= "img Preview "class=" thumbnail "src=" @Model. Commonmodel.defaultpicurl "/&gt; @Html. Hiddenfor (model =&gt; model. CommonModel.defaultpicurl) &lt;a id= "Btn_picselect" class= "Easyui-linkbutton" &gt; select ...&lt;/a&gt; @Html. ValidationMessageFo R (model =&gt; model. Commonmodel.defaultpicurl) &lt;/div&gt; &lt;/div&gt; &lt;div class= "Form-group" &gt; &lt;div class= "col-sm-offse T-2 col-sm-10 "&gt; &lt;input type=" Submit "value=" Save "class=" btn btn-default "/&gt; &lt;/div&gt; &lt;/div&gt; &L

 T;/div&gt;}

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 &amp;&amp; article. CommonModel.DefaultPicUrl.IndexOf (_filepath) &gt;= 0) | | Article. Content.indexof (_filepath) &gt; 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

&lt;script type= "Text/javascript" &gt; $ ("#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 &lt; 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 &lt; 1) {$.messager.alert ("hint", "No row selected!");
  Return else if (Rows.length &gt; 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

 }} &lt;/script&gt;

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

&lt;summary&gt;///article List json "pay attention to permissions issues, can ordinary people access?" 
  "///&lt;/summary&gt;///&lt;param name=" title "&gt; title &lt;/param&gt;///&lt;param name=" input "&gt; Entry &lt;/param&gt; &lt;param name= "category" &gt; Column &lt;/param&gt;///&lt;param name= "FromDate" &gt; Date &lt;/param&gt;///&lt;param Name= "ToDate" &gt; Date stop &lt;/param&gt;///&lt;param name= "pageIndex" &gt; Page &lt;/param&gt;///&lt;param name= "PageSize" & gt; per-page Records &lt;/param&gt;///&lt;returns&gt;&lt;/returns&gt; public actionresult jsonlist (string title, string input, Nul lable&lt;int&gt; category, Nullable&lt;datetime&gt; fromdate, nullable&lt;datetime&gt; 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 =&gt; 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 (); ///&lt;summary&gt;///My articles list///&lt;/summary&gt;///&lt;param name= "title" &gt;&lt;/param&gt;///&lt;para M name= "FromDate" &gt;&lt;/param&gt;///&lt;param name= "toDate" &gt;&lt;/param&gt;///&lt;param-name= "PageIndex" &gt;& lt;/param&gt;///&lt;param name= "pageSize" &gt;&lt;/param&gt;///&lt;returns&gt;&lt;/returns&gt; public Actionresul T Myjsonlist (string title, Nullable&lt;datetime&gt; fromdate, nullable&lt;datetime&gt; 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 =&gt; 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 &lt;div id= "Toolbar" &gt; &lt;div&gt; &lt;a href= "#" class= "Easyui-linkbutton" data-options= "iconcls: ' I Con-edit ', plain:true "onclick=" Eidt () "&gt; Modify &lt;/a&gt; &lt;a href=" # "class=" Easyui-linkbutton "data-options=" Iconcls: ' Icon-remove ', Plain:true ' onclick= "del ()" &gt; Delete &lt;/a&gt; &lt;a href= "#" class= "Easyui-linkbutton" data-options= "Iconcls: ' Icon-reload ', plain:true" onclick= "$ (' #article_list '). DataGrid (' reload '); &gt; Refresh &lt;/a&gt; &lt;/div&gt; &lt;div class= "Form-inline" &gt; &lt;label&gt; title &lt;/label&gt; &lt;input id= "Textbox_title" class= "Input-easyui" style= "width:280px"/&gt; &lt;label&gt; Add date &lt;/label&gt; &lt;input id= "datebox_fromdate" type= "datetime" class= "Easyui-datebox" style= "width:120px"/&gt;-&lt; Input id= "datebox_todate" type= "datetime" class= "Easyui-datebox" style= "width:120px"; "/&gt; &lt;a href=" # "id=" Btn_search "data-options=" iconcls: ' Icon-search ' "class=" Easyui-linkbutton "&gt; Query &lt;/a &gt; &lt;/div&gt; &lt;/div&gt; &lt;table id= "article_list" &gt;&lt;/table&gt; &lt;script src= "~/scripts/common.js" &gt;&lt;/script&gt; &lt;script type= "Text/javascript" &gt; $ ("#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 &lt; 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 &lt; 1) {$.messager.alert ("hint", "No row selected!");
  Return else if (Rows.length &gt; 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 }} &lt;/script&gt;

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.

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.