1.如何讓Controller不返回視圖?(比如僅執行一些資料庫操作)
很簡單,只要在Controller中定義一個void類型的public方法即可
public void DeleteData(){ using (SQLiteConnection conn = new SQLiteConnection("Data Source=" + Server.MapPath(_dbFile))) {conn.Open();SQLiteCommand cmd = conn.CreateCommand();cmd.CommandText = "delete from Products";cmd.ExecuteNonQuery(); } //順便給個sqlite使用事務的代碼 //using (SQLiteConnection conn = new SQLiteConnection("Data Source=" + Server.MapPath(_dbFile))) //{//conn.Open();//SQLiteTransaction t = conn.BeginTransaction();//try//{ //SQLiteCommand cmd = conn.CreateCommand(); //cmd.CommandText = "insert into Products(Name,CreateDate,UpdateDate) values(@Name,@CreateDate,@UpdateDate)"; //for (int i = 0; i < 50; i++) //{//cmd.Parameters.Clear();//cmd.Parameters.AddWithValue("Name", i.ToString().PadLeft(5, '0'));//cmd.Parameters.AddWithValue("CreateDate", DateTime.Now);//cmd.Parameters.AddWithValue("UpdateDate", DateTime.Now);//cmd.ExecuteNonQuery(); //} //t.Commit();//}//catch//{ //t.Rollback();//} //}}
這樣就行了,調用方法類似 : http://localhost/Product/DeleteData 即可
2.如何讓視圖返回純文字或Xml?
public ActionResult GetTxt() { return new ContentResult() { ContentType = "text/plain", ContentEncoding = Encoding.UTF8, Content = "Hello World!" };}
如果要返回xml,把text/plain改為text/xml即可.
3.如何把DataTable傳給視圖?
雖然很多官方教程都是推薦使用強型別的視圖,但是需求是千變萬化的,如果確實要傳遞DataTable給視圖,可參考下面這個做:
public ActionResult Index(){ DataTable tbl = new DataTable(); using (SQLiteConnection conn = new SQLiteConnection("Data Source=" + Server.MapPath(_dbFile))) {SQLiteDataAdapter da = new SQLiteDataAdapter("Select * from Products", conn);da.Fill(tbl);ViewData["data"] = tbl; } return View();}
然後在視圖上可以這樣寫:
<% DataTable tbl = ViewData["data"] as DataTable; foreach (DataRow dr in tbl.Rows) {//... }%>
4.如何使用自訂控制項(做為資料顯示模板)?
建立一個Partial View(局部視圖),內容可參考這樣:
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %><%@ Import Namespace="System.Data" %><tr> <td> <%=(ViewData.Model as DataRow)["Id"] %> </td> <td> <%=(ViewData.Model as DataRow)["Name"]%> </td> <td> <%=(ViewData.Model as DataRow)["CreateDate"]%> </td> <td> <%=(ViewData.Model as DataRow)["UpdateDate"]%> </td></tr>
然後在主視圖中可這樣使用:
<table><tr> <th>Id </th> <th>Name </th> <th>CreateDate </th> <th>UpdateDate </th></tr><% DataTable tbl = ViewData["data"] as DataTable; foreach (DataRow dr in tbl.Rows) {Html.RenderPartial("~/Views/Product/ProductData.ascx", dr); }%></table>
5.頁面/視圖之間如何跳轉?
分二種情況:
void類型的action(即問題1中所說的不返回視圖的action):
有且只有一種方法:
Response.Redirect("/product/Index");
注意:
如果寫成Redirect("/product/Index"); 編譯也會通過,但是根本不會有效果,因為前面不加Response.則變成了Controller類的Redirect方法,這個是有傳回值的,必須用return Redirect()調用才會有效果,但是該方法又是void類型的,不允許return,所以才說這是有且僅有的一種方法.
常規返回ActionResult的action:
方法就很多了:
public ActionResult ShowView1(){ Response.Redirect("ShowView2"); //方法1 //return Redirect("ShowView2"); //方法2 //return RedirectToAction("ShowView2"); //方法3 return View("ShowView2"); //方法4}public ActionResult ShowView2(){ ViewData["data"] = "View2"; return View();}