2015-04-14 47 views
1

我试图在视图页面中显示图像,但它不显示在浏览器中。 这是我的代码: MyChat.cshtml使用Url.Action在视图页面中不显示图像

<td> 
<img src="@Url.Action("GetImage", "Mailbox", new { name = Session["Loginname"].ToString() })" id="photo"/> 
</td> 

控制器

public FileContentResult GetImage(string name) 
{ 
    byte[] cover = GetImageFromDataBase(name); 
    ViewData["image"] = cover; 
    if (cover != null) 
    { 
     return File(cover, "image/jpeg"); 
    } 
    else 
    { 
      return null; 
    } 
} 

public byte[] GetImageFromDataBase(string name) 
{ 
    RegisterLogic logic = new RegisterLogic(); 
    byte[] image = logic.GetImage(name); 
    return image; 
} 

我用于从SQL服务器2008 R2检索值的业务逻辑是:

public byte[] GetImage(string name) 
     { 
      con.ConnectionString = str; 
      cmd.Connection = con; 
      if (con.State == ConnectionState.Open) 
       con.Close(); 
      if (con.State == ConnectionState.Closed) 
       con.Open(); 
      cmd.CommandText = "Select Picture from InspiniaMessage where UserName='" + name + "'"; 
      cmd.CommandType = CommandType.Text; 


      SqlDataAdapter sda = new SqlDataAdapter(cmd); 
      DataTable dt = new DataTable(); 
      sda.Fill(dt); 
      Message m = new Message();   
      foreach (DataRow dr in dt.Rows) 
      { 
       Message mn = new Message(); 
       mn.Picture = (byte[])(dr["Picture"]); 
       m.Picture = mn.Picture;    

      }   
      return m.Picture; 
      con.Close(); 
     } 
    } 

我没有任何错误,但图像不显示在视图中。

+0

看到这一点: http://stackoverflow.com/questions/29576699/how-to-return-url-string-from-controller- a-controller-in-mvc-4/29577189#29577189 –

回答

0

Url.Action产生针对控制器的动作url,它从不会调用动作,对于调用动作您必须使用Html.Action()帮助器。

当你写:

@Url.Action("ActionName","ControllerName")

它返回的URL作为字符串是这样的:

localhost/Controller/Action 

使用Html.Action(),你要执行的动作:

<img src="@Html.Action("GetImage", 
         "Mailbox", 
         new 
         { 
         name = Session["Loginname"].ToString() 
         })" 
    id="photo"/> 
+0

它给出错误'执行处理程序'System.Web.Mvc.HttpHandlerUtil + ServerExecuteHttpHandlerAsyncWrapper'的子请求时出错。你能帮我解决这个问题吗?如何整理出来。 –

+0

在你的动作中加入了断点,看看它是否被调用 –