目录
一、文件上传、下拉框、富文本与模板视图
- MVC中的文件上传
- 步骤1:构造文件上传的表单
<form action="/File" enctype="multipart/form-data" method="post"/> <input type="file" name="file"> <input type="submit" name="upload" value="提交"> </form> | | ↓ <div> @using(Html.BeginForm("Index","File",FormMethod.Post,new {enctype="multipart/form-data"})) { <input type="file" name="file"> <input type="submit" name="upload" value="提交"> } </div>
-
步骤2:接收文件上传数据:利用动作方法参数映射功能,直接将文件映射为HttpPostFileBase类型,该类型是抽象类,包含如下成员
属性或方法 说 明 int ContentLength{get;} 获取上载的文件大小 string ContentType{get;} 获取上载文件的MIME内容类型 string FileName{get;} 获取客户端上载文件的完全限定名 Stream InputStream{get;} 获取Stream对象,该对象指向一个上载文件 void SaveAs(string fileName) 保存上载文件的内容 MIME类型就是设定某种扩展名的文件用一种应用程序来打开的方式类型,当该扩展名文件被访问时,浏览器会使用指定的应用程序来打开
//编写控制器 public ActionResult Index(HttpPostedFileBase file) { if(file != null) { string filePath = Server.MapPath("~/files/")+file.FileName;//获取文件在服务器的路径 file.SaveAs(filePath);//将文件保存至此路径 return Content("<script>alert('文件上传成功');location.href = "'+Url.Content("~/File")+'"</script>"); } return View("Index"); }
- 步骤1:构造文件上传的表单
二、下拉列表动态填充
- 思路:
- 构造数据源
- 使用IEnumerable<SelectListItem>数据源:直接在视图中固定内容,适合静态下拉框
namespace System.Web.Mvc { public class SelectListItem { public SelectListItem(); public bool Selected{get;set;}//是否选中 public string Text{get;set;}//内容项文本 public bool Value{get;set;}//内容项值 } } @using(Html.BeginForm("AddNews","News",FormMethod.Post)) { var items = new List<SelectListItem>(); items.Add(new SelectListItem(){Text = "教育",Value = "1"}); items.Add(new SelectListItem(){Text = "军事",Value = "2",Selected = true}); items.Add(new SelectListItem(){Text = "汽车",Value = "3"}); <ul> <li>新闻标题:@Hteml.TextBox("NewTitle",null,new {@calss = "title"})</li> <li>新闻分类:@Hteml.DropDownList("NewCatrgory",items,"请选择")</li> <li class="txtarea"> 详细内容:@Html.TextArea("NewsCotent",null,new{@class="txtarea"}) </li> </ul> }
- 使用IEnumerable<SelectListItem>数据源:直接在视图中固定内容,适合静态下拉框
- 使用视图辅助方法:Html.DropDownList():使用SelectList数据源,从数据库获取数据,构造函数 public SelectList(IEnumerable Items,string dataValueField,string dataTextFiled,object selectedValue)//数据源,数据值字段,数据文本字段,选定值
namespace System.Web.Mvc { public class NewCategory { public int CategoryId{get;set;} public string CategoryName{get;set;}//内容项文本 public NewCategory(int id,string name) { this.CategoryId = id; this.CategoryName = name; } } } public ActionResult Index() { List<NewCategory> category = new NewServer().GetNewInfo(); SelectList list = new SelectList(category,"CategoryId","CategoryName",category[0].Category); ViewBag.Category = list; return View("AddNews"); } @using(Html.BeginForm("AddNews","News",FormMethod.Post)) { <ul> <li>新闻标题:@Hteml.TextBox("NewTitle",null,new {@calss = "title"})</li> <li>新闻分类:@Hteml.DropDownList("NewCatrgory",(SelectList)ViewBag.Category,"请选择")</li> <li class="txtarea"> 详细内容:@Html.TextArea("NewsCotent",null,new{@class="txtarea"}) </li> </ul> }
- 构造数据源
三、富文本编辑器ckeditor
- CkEditor简介
- 一款开源的所见即所得的文字编辑器,轻量级,无需安装
- 使用方法
四、Razor母版视图
母版视图用于提前设置页面中不变的内容,如整体布局等
- 创建