[英]Calling method from MVC view does not work
我熟悉C#/ .net,但是對於.net mvc和razor的東西很新,我想要做的是,我想從視圖中調用控制器中的方法,將字符串路徑呈現為二進制,所以我在視圖中這樣做:
<img src="@Url.Action("ReadFile", "FLK", new { path = Model.Pict })" />
這在控制器中:
public void ReadFile(string path)
{
Response.ContentType = "image";
Response.BinaryWrite(System.IO.File.ReadAllBytes(path));
}
但是當我在控制器中放置一個調試點時,我的調試點從來沒有任何線索,任何線索? 需要一些建議,謝謝。
控制器中的ReadFile()
方法應該是這樣的 -
public ActionResult ReadFile(string path)
{
byte[] imgBytes = System.IO.File.ReadAllBytes(path);
return File(imgBytes, "image/png");
}
這里,您的action方法將圖像文件讀入字節數組,然后使用ActionResult基類的File()方法將內容發送給調用者。
所以你可以在你的視圖中使用它 -
<img src='@Url.Action("ReadFile", new { path = Model.Pict }))'/>
您的控制器方法應如下所示。
[HttpGet]
public ActionResult ReadFile(string path)
{
return new FileContentResult(System.IO.File.ReadAllBytes(Server.MapPath(path)), "image");
}
視圖中的代碼是可以的。 但要確保圖像的路徑類似於“〜\\ Images \\ Test.png”; 現在控制器中的斷點將被擊中。 在客戶端瀏覽器中加載頁面時會觸發它。
public FileContentResult getImage(int id)
{
byte[] imgBytes = System.IO.File.ReadAllBytes(path);
if (imgBytes!= null)
{
return new FileContentResult(imgBytes, "image/jpeg");
}
else
{
return null;
}
}
關於剃刀
<img src="@Html.Action("ReadFile", "FLK", new { path = Model.Pict })" />
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.