一、项目需求
评论规则的设立是为了规范用户的行为,维护社交媒体和其他在线平台上的秩序。
B站视频教程
评论-录入评论规则
二、添加评论规则
1、搭建SQL Server数据库环境
NetDB数据库,新建 CommentRule 表
id int (主键)
text nvarchar
isMod bit //审查词
isForbid bit //禁用词
replaceWord nvarchar //替换词
createDate datetime
isDelete bit //逻辑删除
2、更新实体数据模型
Model1.edmx→从数据库更新模型
3、添加数据注解
public partial class CommentRule
{
public int id { get; set; }
[DisplayName("文本")]
[Required]
public string text { get; set; }
[DisplayName("审查词")]
public bool isMod { get; set; } = false;
[DisplayName("禁用词")]
public bool isForbid { get; set; } = false;
[DisplayName("替换词")]
public string replaceWord { get; set; } = "";
[ScaffoldColumn(false)]
public System.DateTime createDate { get; set; }
[ScaffoldColumn(false)]
public bool isDelete { get; set; }
}
public partial class Product
{
public int id { get; set; }
[DisplayName("产品名称")]
[Required]
public string name { get; set; }
[DisplayName("生产日期")]
[Required]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public System.DateTime pDate { get; set; }
[DisplayName("生成人")]
[Required]
public string pWork { get; set; }
[DisplayName("价格")]
[Required]
[DataType(DataType.Currency)]
public decimal price { get; set; }
}
4、评论规则首页
@using Webdiyer.WebControls.Mvc
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div style="margin-bottom:10px">
@using (Ajax.BeginForm("AjaxPage", "CommentRule", new AjaxOptions
{
UpdateTargetId = "ajaxDiv",
InsertionMode = InsertionMode.Replace
}, new { @class = "form-inline", id = "searchForm" }))
{
@Html.TextBox("queryStr", "", new { placeholder = "关键词", @class = "form-control", style = "width:200px" })
@Html.Raw(" ")
@Html.TextBox("submit", "搜索", new { type = "submit", @class = "btn btn-default", onclick = "return beforeSearch()" })
}
</div>
<div id="ajaxDiv">
@Html.Action("AjaxPage","CommentRule")
</div>
@section scripts
{
@{Html.RegisterMvcPagerScriptResource();}
}
5、 查询加分页
1)AjaxPage Action
private NetDBEntities dbContext = new NetDBEntities();
public ActionResult AjaxPage(string queryStr = "",int pageIndex=1,int pageSize=10)
{
IQueryable<CommentRule> commentRuleQueryable = dbContext.CommentRules.Select(cr => cr);
if (queryStr.Trim().Length > 0)
{
commentRuleQueryable = commentRuleQueryable.Where(cr => cr.text.Contains(queryStr.Trim()));
}
commentRuleQueryable = commentRuleQueryable.OrderByDescending(cr => cr.createDate);
PagedList<CommentRule> commentRulePagedList = commentRuleQueryable.ToPagedList(pageIndex, pageSize);
commentRulePagedList.TotalItemCount = commentRuleQueryable.Count();
return PartialView("_AjaxPage", commentRulePagedList);
}
2)_AjaxPage cshtml
@using Webdiyer.WebControls.Mvc
@model PagedList<CommentProject.Models.CommentRule>
@{Html.RenderPartial("_List", Model);}
<div class="row">
<div class="col-sm-3 col-sm-offset-1" style="line-height: 5.428571; ">
共 @Model.TotalPageCount 页 @Model.TotalItemCount 条记录,当前为第 @Model.CurrentPageIndex 页
</div>
<div class="col-sm-8">
@Ajax.Pager(Model, new PagerOptions
{
PageIndexParameterName = "pageIndex",
ContainerTagName = "ul",
CssClass = "pagination",
CurrentPagerItemTemplate = "<li class=\"active\"><a href=\"#\">{0}</a></li>",
DisabledPagerItemTemplate = "<li class=\"disabled\"><a>{0}</a></li>",
PagerItemTemplate = "<li>{0}</li>"
}).AjaxOptions(a => a.SetUpdateTargetId("ajaxDiv").SetDataFormId("searchForm"))
</div>
</div>
3)_List cshtml
@using Webdiyer.WebControls.Mvc
@model PagedList<CommentProject.Models.CommentRule>
@{
int index = (Model.CurrentPageIndex - 1) * Model.PageSize + 1;
}
6、批量导入功能
1)表单 Index cshtml
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="row" style="margin-bottom:10px">
<div class="col-sm-4">
<form action="/CommentRule/BatchCreate" enctype="multipart/form-data" method="post" class="form-inline">
<input name="file" id="file" type="file" accept=".txt" style="display: inline-block" />
<input value="导入" type="submit" class="btn btn-primary" onclick="return beforeSubmit()" />
</form>
</div>
<div class="col-sm-2">
@Html.ActionLink("新增", "Create", new { }, new { @class = "btn btn-success" })
</div>
</div>
<script type="text/javascript">
function beforeSubmit() {
if ($("#file").val().length == 0) {
alert("请选择需要上传的txt文件");
return false;
}
}
</script>
2)BatchCreate Action
[HttpPost]
public ActionResult BatchCreate() {
//数据库中有记录时,不支持批量导入
int count = dbContext.CommentRules.Count();
if (count > 0)
{
ModelState.AddModelError("", "数据库中有记录时,不支持批量导入");
return View("index");
}
//上传文件
HttpPostedFileBase httpPostedFile = Request.Files["file"];
if (httpPostedFile == null || httpPostedFile.ContentLength <= 0)
{
//return JavaScript("alert('文件不能为空')");
ModelState.AddModelError("", "文件不能为空");
return View("index");
}
string fileName = Guid.NewGuid() + httpPostedFile.FileName;
string path = AppDomain.CurrentDomain.BaseDirectory + "Upload";
try
{
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
string savePath = Path.Combine(path, fileName);
httpPostedFile.SaveAs(savePath);
List<CommentRule> commentRules = new List<CommentRule>();
// 使用 StreamReader 读取文件内容
using (StreamReader sr = new StreamReader(savePath))
{
int i = 0;
string line;
while ((line = sr.ReadLine()) != null)
{
CommentRule commentRule = new CommentRule();
string[] strArr = line.Split('=');
commentRule.text = strArr[0];
if (strArr[1].Equals("{BANNED}"))
{
commentRule.isForbid = true;
}
else if (strArr[1].Equals("{MOD}"))
{
commentRule.isMod = true;
}
else
{
commentRule.replaceWord = strArr[1];
}
commentRule.createDate = DateTime.Now;
commentRule.isDelete = false;
commentRules.Add(commentRule);
i++;
//读取txt文本,存入list
if (i % 100 == 0)
{
//批量入库
dbContext.CommentRules.AddRange(commentRules);
dbContext.SaveChanges();
commentRules.Clear();
}
}
}
if (commentRules.Count > 0)
{
dbContext.CommentRules.AddRange(commentRules);
dbContext.SaveChanges();
}
}
catch (Exception ex)
{
ModelState.AddModelError("", ex.Message);
return View("index");
}
return RedirectToAction("index");
}
7、新增(单个)功能
[HttpPost]
public ActionResult Create(CommentRule commentRule)
{
if (!ModelState.IsValid) return View(commentRule);
if (String.IsNullOrEmpty(commentRule.replaceWord))
{
commentRule.replaceWord = "";
}
if (!commentRule.isMod && !commentRule.isForbid && commentRule.replaceWord.Trim().Length == 0)
{
ModelState.AddModelError("", "数据校验失败");
return View();
}
if (dbContext.CommentRules.Count(cr => cr.text.Equals(commentRule.text.Trim())) > 0)
{
ModelState.AddModelError("", "评论规则已存在");
return View();
}
commentRule.createDate = DateTime.Now;
commentRule.isDelete = false;
dbContext.CommentRules.Add(commentRule);
dbContext.SaveChanges();
return RedirectToAction("Index");
}