冯 海

一个程序新人菜鸟的日记,希望大家多多关照。QQ:32316131

mvc5+ef+ adminlte教程17:mvc5 用正则表达式获取字段中的图片地址取出来形成列表

今日头条那样,上面是文章下面是图很好漂亮。

所以我思考半天,准备将CmsContents表再增加一个字段,前台的Ueditor送过去的字段内容,进行处理,将其图片地址用正则表达式取出来存入另一个字段。

然后前台直接LIst<>这个字段进行图片的展示。

下一步还可以考虑将图片生成浓缩图。

1.先增加一个字段。进行first code.
	public string Piclist { get; set; }
2.控制器,对model.Contetnts字段进行遍历,对所有的图片地址写入字段piclist,同时用","分隔。
// POST: CmsContents/Create
        // 为了防止“过多发布”攻击,请启用要绑定到的特定属性,有关 
        // 详细信息,请参阅 https://go.microsoft.com/fwlink/?LinkId=317598。
        [HttpPost]
        [ValidateAntiForgeryToken]
		[ValidateInput(false)]
		public async Task<ActionResult> Create([Bind(Include = "ColumnId,Title,Contents,CmsPermission")] CmsContent cmsContent, FormCollection form)
        {
		    var	 dt = DateTime.Now;
			string str = dt.ToString("yyyyMMddHHmmss");
			cmsContent.Id = str;
	 
			cmsContent.PcIp = Request.UserHostAddress;
			cmsContent.CreatUser = Session["username"].ToString();
			cmsContent.ReplyCount =0;
			cmsContent.CreatTime = DateTime.Now;
			cmsContent.yulou1 = Session["headerPic"].ToString();

			var winnars = from x in form.AllKeys        ///选择所有的传进来的form

							  //var winnars = from x in form["selectRole"]
						  where form[x] != "false"

						  select x;
		 
			string Lstring = "";
			 
			//foreach (var id in winnars)
			foreach(var id in winnars)
			{
				if (id != "Contents" && id != "ColumnId" && id != "Title" && id != "Id" && id != "ReplyCount" && id != "CreatUser" && !id.Contains("RequestVerificationToken"))
				{
					Lstring = Lstring + id + ",";
				}

			}
			cmsContent.CmsPermission = Lstring;
			///用正则表达式获取Ueditor中送过来的Contents字段中的图片列表。
			 
			Regex m_hvtRegImg = new Regex(@"<img\b[^<>]*?\bsrc[\s\t\r\n]*=[\s\t\r\n]*[""']?[\s\t\r\n]*(?<imgUrl>[^\s\t\r\n""'<>]*)[^<>]*?/?[\s\t\r\n]*>", RegexOptions.IgnoreCase);
			String yyyy = cmsContent.Contents;
			// 搜索匹配的字符串 
			MatchCollection matches = m_hvtRegImg.Matches(yyyy);
			int m_i = 0;
			string[] sUrlList = new string[matches.Count];
			// 取得匹配项列表 
			foreach (Match match in matches)
			{
				sUrlList[m_i++] = match.Groups["imgUrl"].Value;
			}
			cmsContent.Piclist = string.Join(",",sUrlList);
			 


			//END 获取图片地址

			if (ModelState.IsValid)
            {
                db.CmsContents.Add(cmsContent);
                await db.SaveChangesAsync();
                return RedirectToAction("Admin","User");
            }

            return View(cmsContent);
        }
3.前台,用Model.PicList进行.split(',')
<table class="table  table-hover" style="table-layout:fixed">
			<tr>
				<th width="80%"></th>
				<th></th>
			</tr>
			@foreach (var item in Model)
			{
				<tr>
					<td style="overflow:hidden;white-space:nowrap;text-overflow:ellipsis;">
						<a href="~/CmsContents/Details?id=@item.Id">	@Html.DisplayFor(modelItem => item.Title)</a>
						<br />
						@{
							if (item.Piclist != null)
							{
								string[] picList = item.Piclist.Split(',');
								for (var a = 0; a < picList.Length; a++)
								{
									 <img src= @picList[a] width="145" height="95" />
								}

							}
						}

					</td>
					<td>
						@Html.DisplayFor(modelItem => item.CreatTime, "DateTimeTemplate")
					</td>
				</tr>
			}
		</table>

  

 4.效果。

 

 

余下的就是美化了。

先保存一下,再上修改完后的代码。

 下面完整的视图

@*@model IEnumerable<jsdhh2.Models.CmsContent>*@
@model PagedList.IPagedList<jsdhh2.Models.CmsContent>
@using PagedList.Mvc;
<link href="~/Content/PagedList.css" rel="stylesheet" />

@{
	ViewBag.Title = "Index";
}

<div class="dhhheight1 col-md-12 col-xs-12"></div>
<!--start 左 -->
<div class="col-md-3">
	@using (Html.BeginForm("indexList", "CmsContents", new { @class = "form-inline" }, FormMethod.Post))
	{	<div class="dhhheight1 col-md-12 col-xs-12">.</div>

	<div class="form-inline dhhbootom">
		<div class="form-group">
			<div class="input-group col-md-12">
				@Html.TextBox("SearchString", "", new { @class = "form-control", @Style = "display:inline" })
				<span class="input-group-btn ">
					<input id="btnSearch" class="btn btn btn-primary" type="submit" value="搜索">
				</span>
			</div>
		</div>
	</div>
	}
	.
	<div class="box box-solid">
		<div class="box-header with-border">
			<h3 class="box-title">文章中心</h3>

			<div class="box-tools">
				<button type="button" class="btn btn-box-tool" data-widget="collapse">
					<i class="fa fa-minus"></i>
				</button>
			</div>
		</div>
		<div class="box-body no-padding" style="display: block;">
			<ul class="nav nav-pills nav-stacked">

				@foreach (jsdhh2.Models.CmsColumn data1 in (ViewBag.drolistmenu as IEnumerable<jsdhh2.Models.CmsColumn>
))
				{

					<li>
						<a href="~/CmsContents/IndexList?SeachColumnString=@data1.Id"><i class="fa fa-circle-o"></i> @data1.Name</a>

					</li>
				}

			</ul>
		</div>
		<!-- /.box-body -->

	</div>







</div>

<!--start 右 -->
<div class="col-md-9 col-xs-12 pull-right">

	<!-- Content Header (Page header) -->
	<section class="content-header">
		<h1>
			文章列表
			<small>文章千万篇,我只取三千~</small>

		</h1>

		<ol class="breadcrumb">
			<li><a href="#"><i class="fa fa-dashboard"></i> Level</a></li>
			<li class="active">Here</li>
		</ol>
	</section>
	<!--end Content Header (Page header) -->
	<!-- Main content -->
	<section class="content">

		<table class="table  table-hover" style="table-layout:fixed">
			<tr>
				<th width="80%"></th>
				<th></th>
			</tr>
			@foreach (var item in Model)
			{
				<tr>
					<td style="overflow:hidden;white-space:nowrap;text-overflow:ellipsis;">
						<div  class="dhhlisttile">	<a href="~/CmsContents/Details?id=@item.Id"> 	@Html.DisplayFor(modelItem => item.Title) </a></div>
						
						@{
							if (item.Piclist != null)
							{ 
								string[] picList = item.Piclist.Split(',');
								for (var a = 0; a < picList.Length; a++)
								{
									 <img src= @picList[a] width="145" height="95" style="margin-right:9px;" />
								}

							}
						}
						 <div style="line-height:30px; color:#c3c2c2;">by @item.CreatUser 于 @Html.DisplayFor(modelItem => item.CreatTime, "DateTimeTemplate")</div>
					</td>
				 
				</tr>
			}
		</table>

 <!-- /.box -->
		<!-- Main content -->
							Page @(Model.PageCount < Model.PageNumber ? 0 : Model.PageNumber) of @Model.PageCount
							@Html.PagedListPager(Model, page => Url.Action("IndexList",
  new { page, SeachColumnString = ViewBag.SeachColumnString, SearchString = ViewBag.SearchString }))

						</section>

					</div>

					@section Scripts {
						<script type="text/JavaScript">
							function GetImgUrl(imgstr) {
								var r = /<img[^>]+?src=(/"|/')([^/'/"]+)/1/i;
								alert(imgstr.match(r)[2]);
							}
						</script>


					}

  然后更改了jsdhh.css中的几个CSS

.dhhlisttile {
	font-size: 24px;
	line-height: 42px;
	 
}
 .dhhlisttile a{
	color:#000000;
	}

  效果

posted @ 2017-06-21 17:16  秋天来了哟  阅读(211)  评论(0编辑  收藏  举报
认识就是缘份,愿天下人都快乐!
QQ: 32316131
Email: 32316131@qq.com