ASP.NET MVC幾個常件的ActionResult的範例

ASP.NET MVC幾個常件的ActionResult的範例

剛從資策會畢業,第一個專案就是ASP MVC,所以整理了一下,MVC幾個常用的ActionResult

ActionResult

ActionResult

public ActionResult PasswordError()

{

return View();

}

Javscript()

public JavaScriptResult ForJavaScriptResult()

{

//string js = "alert(\"這是JavascriptResult的結果\")";

//string js = "Javascript:alert(123)";

//return JavaScript(js);

return JavaScript("alert('Java script')");

}

FilePathResult()

public FilePathResult ForFilePathResult()

{

// ../ 上一層

// ../../ 上兩層

// ../../../ 上三層

var imgPath = Server.MapPath("~/");

return File(imgPath + "example.jpg", "image/png");

}

DownloadFile()

public ActionResult DownloadFile()//下載檔案,FileStream 只能用內部

{

Stream iStream = new FileStream(Server.MapPath("~/example.jpg"), FileMode.Open, FileAccess.Read, FileShare.Read);

return File(iStream, "image/png", "1.jpg");

// return JavaScript("alert(\"無此檔案\")");

}

JsonResult ForJsonResult()

public JsonResult ForJsonResult()

{

var JsonContent = new { Id = 1, Content = "這是JsonResult" };

return Json(JsonContent, JsonRequestBehavior.AllowGet);

}

Upload(單檔)

[HttpPost]

public ActionResult Upload(HttpPostedFile file)

{

if (file != null)

{

if (file.ContentLength > 0)

{

string url = Path.Combine(Server.MapPath("~/Uploads/"), file.FileName); //路徑合併

file.SaveAs(url);

}

}

return RedirectToAction("Upload");

}

Upload(多檔案上傳)

[HttpPost]

public ActionResult Upload(IEnumerable<HttpPostedFile> files)

{

foreach (var file in files)

{

if (file != null && file.ContentLength > 0)

{

string filePath = DateTime.Now.ToLongDateString() + file.FileName;

string url = Path.Combine(Server.MapPath("~/Uploads/"), filePath); //路徑合併

file.SaveAs(url);

}

}

return RedirectToAction("Upload");

}