目錄
一、文件上傳、下拉框、富文本與模板視圖
- 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母版視圖
母版視圖用於提前設置頁面中不變的內容,如整體佈局等
- 創建