图像未使用Url.Action显示在视图页面中

时间:2015-04-14 12:02:34

标签: c# asp.net-mvc asp.net-mvc-4

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

<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 Server 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();
        }
     }

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

1 个答案:

答案 0 :(得分: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"/>