1

I am trying to display image in view page but it doesn't display in the browser. Here is my code: MyChat.cshtml

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

Controller

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;
}

The Business logic i used for retrieving the values from SQL server 2008 R2 is as:

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

I have not got any error but the image not displays in the view.

1

1 Answer 1

0

Url.Action generates url for action against the controller, it never calls the action, for calling action you will have to use Html.Action() helper.

when you write:

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

it return url as string like this:

localhost/Controller/Action

Use Html.Action() as you want to execute action:

<img src="@Html.Action("GetImage", 
                       "Mailbox", 
                      new 
                        { 
                         name = Session["Loginname"].ToString() 
                        })" 
     id="photo"/>
Sign up to request clarification or add additional context in comments.

1 Comment

it gives error Error executing child request for handler 'System.Web.Mvc.HttpHandlerUtil+ServerExecuteHttpHandlerAsyncWrapper. could you help me on this. how to sort this out.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.