当前位置: 移动技术网 > IT编程>开发语言>.net > ASP.NET MVC5网站开发修改及删除文章(十)

ASP.NET MVC5网站开发修改及删除文章(十)

2017年12月12日  | 移动技术网IT编程  | 我要评论

上次做了显示文章列表,再实现修改和删除文章这部分内容就结束了,这次内容比较简单,由于做过了添加文章,修改文章非常类似,就是多了一个tryupdatemodel部分更新模型数据。
一、删除文章
由于公共模型跟,文章,附件有关联,所以这里的删除次序很重要,如果先删除模型,那么文章modelid和附件的modelid多会变成null,所以要先先删除文章和附件再删除公共模型。

由于公共模型和附件是一对多的关系,我们把删除公共模型和删除附件写在一起。

在bll的baserepository类中有默认的delete方法,但这个方法中仅删除模型,不会删除外键,所以在commonmodelrepository在new一个出来封印掉默认的方法。

public new bool delete(models.commonmodel commonmodel, bool issave = true)
  {
   if (commonmodel.attachment != null) ncontext.attachments.removerange(commonmodel.attachment);
   ncontext.commonmodels.remove(commonmodel);
   return issave ? ncontext.savechanges() > 0 : true;
  }

这个的意思是封印掉继承的delete方法,在新的方法中如果存在附加那么先删除附件,再删除公共模型。那么如果我们还想调用基类的delete方法怎么办?可以用base.delete。

好了,现在可以开始删除了。

在articlecontroller中添加delete方法

/// <summary>
  /// 删除
  /// </summary>
  /// <param name="id">文章id</param>
  /// <returns></returns>
  public jsonresult delete(int id)
  {
   //删除附件
   var _article = articleservice.find(id);
   if(_article == null) return json(false);
   //附件列表
   var _attachmentlist = _article.commonmodel.attachment;
   var _commonmodel = _article.commonmodel;
   //删除文章
   if (articleservice.delete(_article))
   {
    //删除附件文件
    foreach (var _attachment in _attachmentlist)
    {
     system.io.file.delete(server.mappath(_attachment.fileparth));
    }
    //删除公共模型
    commonmodelservice.delete(_commonmodel);
    return json(true);
   }
   else return json(false);
  }

二、修改文章
这个部分跟添加文章非常类似
首先在articlecontroller中添加显示编辑视图的edit

/// <summary>
  /// 修改
  /// </summary>
  /// <param name="id"></param>
  /// <returns></returns>
  public actionresult edit(int id)
  {
   return view(articleservice.find(id));
  }

右键添加视图,这个跟添加类似,没什么好说的直接上代码

@section scripts{
 <script type="text/javascript" src="~/scripts/kindeditor/kindeditor-min.js"></script>
 <script type="text/javascript">
  //编辑框
  kindeditor.ready(function (k) {
   window.editor = k.create('#content', {
    height: '500px',
    uploadjson: '@url.action("upload", "attachment")',
    filemanagerjson: '@url.action("filemanagerjson", "attachment", new { id = @model.commonmodel.modelid })',
    allowfilemanager: true,
    formatuploadurl: false
   });
  //首页图片
   var editor2 = k.editor({
    filemanagerjson: '@url.action("filemanagerjson", "attachment", new {id=@model.commonmodel.modelid })'
   });
   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("生成缩略图失败!");
         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="form-horizontal" role="form">
  <h4>添加文章</h4>
  <hr />
  @html.validationsummary(true)
  <div class="form-group">
   <label class="control-label col-sm-2" for="commonmodel_categoryid">栏目</label>
   <div class="col-sm-10">
    <input id="commonmodel_categoryid" name="commonmodel.categoryid" data-options="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(model => 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="imgpreview" class="thumbnail" src="@model.commonmodel.defaultpicurl" />
    @html.hiddenfor(model => model.commonmodel.defaultpicurl)
    <a id="btn_picselect" class="easyui-linkbutton">选择…</a>
    @html.validationmessagefor(model => model.commonmodel.defaultpicurl)
   </div>
  </div>

  <div class="form-group">
   <div class="col-sm-offset-2 col-sm-10">
    <input type="submit" value="保存" class="btn btn-default" />
   </div>
  </div>
 </div>
}

开始做后台接受代码,在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))
    {
     //附件处理
     interfaceattachmentservice _attachmentservice = 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);
  }

详细讲解一下吧:

1、[validateinput(false)] 表示不验证输入内容。因为文章内容包含html代码,防止提交失败。

2、[validateantiforgerytoken]是为了防止伪造跨站请求的,也就说只有本真的请求才能通过。

见图中的红线部分,在试图中构造验证字符串,然后再后台验证。

3、public actionresult edit()。看这个方法没有接收任何数据,我们再方法中使用tryupdatemodel更新模型。因为不能完全相信用户,比如如果用户构造一个categgoryid过来,就会把文章发布到其他栏目去。

这个是在路由中获取id参数

再看这两行,略有不同
第一行直接更新article模型。第一个参数是要更新的模型,第二个参数是更新的字段。
第二行略有不同,增加了一个前缀参数,我们看视图生成的代码 @html.textboxfor(model => model.commonmodel.title 是带有前缀commonmodel的。所以这里必须使用前缀来更新视图。

三、修改文章列表
写完文章后,就要更改文章列表代码用来删除和修改文章。
打开list视图,修改部分由2处。
1、js脚本部分

<script type="text/javascript">
 $("#article_list").datagrid({
  loadmsg: '加载中……',
  pagination:true,
  url: '@url.action("jsonlist","article")',
  columns: [[
   { field: 'modelid', title: 'id', checkbox: true },
   { field: 'categoryname', title: '栏目'},
   { field: 'title', title: '标题'},
   { field: 'inputer', title: '录入', align: 'right' },
   { field: 'hits', title: '点击', align: 'right' },
   { field: 'releasedate', title: '发布日期', align: 'right', formatter: function (value, row, index) { return jsondateformat(value); } },
   { field: 'statusstring', title: '状态', width: 100, align: 'right' }
  ]],
  toolbar: '#toolbar',
  idfield: 'modelid',
  ondblclickrow: function (rowindex, rowdata) { window.parent.addtab("修改文章", "@url.action("edit","article")/" + rowdata.modelid, "icon-page"); }
 });
 //查找
 $("#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')
  });
 });

 //修改事件
 function eidt() {
  var rows = $("#article_list").datagrid("getselections");
  if (!rows || rows.length < 1) {
   $.messager.alert("提示", "请选择要修改的行!");
   return;
  }
  else if (rows.length != 1) {
   $.messager.alert("提示", "仅能选择一行!");
   return;
  }
  else {
   window.parent.addtab("修改文章", "@url.action("edit","article")/" + rows[0].modelid, "icon-page");
  }
 }
 //删除
 function del()
 {
  var rows = $("#article_list").datagrid("getselections");
  if (!rows || rows.length < 1) {
   $.messager.alert("提示", "未选择任何行!");
   return;
  }
  else if (rows.length > 0) {
   $.messager.confirm("确认", "您确定要删除所选行吗?", 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');
     //清除选择行
     rows.length = 0;
     $("#article_list").datagrid('reload');
    }
   });
   return;
  }
 }
</script>

增加了修改方法、删除方法,在datagrid里添加行双击进入修改视图的方法

ondblclickrow: function (rowindex, rowdata) { window.parent.addtab("修改文章", "@url.action("edit","article")/" + rowdata.modelid, "icon-page"); }

2、

四、我的文章列表
我的文章列表与全部文章类似,并简化掉了部分内容那个,更加简单,直接上代码了
article控制器中添加

/// <summary>
  /// 文章列表json【注意权限问题,普通人员是否可以访问?】
  /// </summary>
  /// <param name="title">标题</param>
  /// <param name="input">录入</param>
  /// <param name="category">栏目</param>
  /// <param name="fromdate">日期起</param>
  /// <param name="todate">日期止</param>
  /// <param name="pageindex">页码</param>
  /// <param name="pagesize">每页记录</param>
  /// <returns></returns>
  public actionresult jsonlist(string title, string input, nullable<int> category, nullable<datetime> fromdate, nullable<datetime> todate, int pageindex = 1, int pagesize = 20)
  {
   if (category == null) category = 0;
   int _total;
   var _rows = commonmodelservice.findpagelist(out _total, pageindex, pagesize, "article", title, (int)category, input, 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() });
  }

  public actionresult mylist()
  {
   return view();
  }

  /// <summary>
  /// 我的文章列表
  /// </summary>
  /// <param name="title"></param>
  /// <param name="fromdate"></param>
  /// <param name="todate"></param>
  /// <param name="pageindex"></param>
  /// <param name="pagesize"></param>
  /// <returns></returns>
  public actionresult myjsonlist(string title, nullable<datetime> fromdate, nullable<datetime> todate, int pageindex = 1, int pagesize = 20)
  {
   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);
  }
为mylist右键添加视图
<div id="toolbar">
 <div>
  <a href="#" class="easyui-linkbutton" data-options="iconcls:'icon-edit',plain:true" onclick="eidt()">修改</a>
  <a href="#" class="easyui-linkbutton" data-options="iconcls:'icon-remove',plain:true" onclick="del()">删除</a>
  <a href="#" class="easyui-linkbutton" data-options="iconcls:'icon-reload',plain:true" onclick="$('#article_list').datagrid('reload');">刷新</a>
 </div>
 <div class="form-inline">
  <label>标题</label> <input id="textbox_title" class="input-easyui" style="width:280px" />
  <label>添加日期</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">查询</a>
 </div>

</div>
<table id="article_list"></table>
<script src="~/scripts/common.js"></script>
<script type="text/javascript">
 $("#article_list").datagrid({
  loadmsg: '加载中……',
  pagination:true,
  url: '@url.action("myjsonlist", "article")',
  columns: [[
   { field: 'modelid', title: 'id', checkbox: true },
   { field: 'categoryname', title: '栏目'},
   { field: 'title', title: '标题'},
   { field: 'inputer', title: '录入', align: 'right' },
   { field: 'hits', title: '点击', align: 'right' },
   { field: 'releasedate', title: '发布日期', align: 'right', formatter: function (value, row, index) { return jsondateformat(value); } },
   { field: 'statusstring', title: '状态', width: 100, align: 'right' }
  ]],
  toolbar: '#toolbar',
  idfield: 'modelid',
  ondblclickrow: function (rowindex, rowdata) { window.parent.addtab("修改文章", "@url.action("edit","article")/" + rowdata.modelid, "icon-page"); }
 });
 //查找
 $("#btn_search").click(function () {
  $("#article_list").datagrid('load', {
   title: $("#textbox_title").val(),
   fromdate: $("#datebox_fromdate").datebox('getvalue'),
   todate: $("#datebox_todate").datebox('getvalue')
  });
 });

 //修改事件
 function eidt() {
  var rows = $("#article_list").datagrid("getselections");
  if (!rows || rows.length < 1) {
   $.messager.alert("提示", "请选择要修改的行!");
   return;
  }
  else if (rows.length != 1) {
   $.messager.alert("提示", "仅能选择一行!");
   return;
  }
  else {
   window.parent.addtab("修改文章", "@url.action("edit","article")/" + rows[0].modelid, "icon-page");
  }
 }
 //删除
 function del()
 {
  var rows = $("#article_list").datagrid("getselections");
  if (!rows || rows.length < 1) {
   $.messager.alert("提示", "未选择任何行!");
   return;
  }
  else if (rows.length > 0) {
   $.messager.confirm("确认", "您确定要删除所选行吗?", 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');
     //清除选择行
     rows.length = 0;
     $("#article_list").datagrid('reload');
    }
   });
   return;
  }
 }
</script>

要注意的是删除文章时删除的次序,修改文章时tryupdatemodel的使用,希望本文对大家的学习有所帮助。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网