Unable to display an image in my view - asp.net

I try to display an image (stored in my database) and I have some trouble with it.
I have the following code in my view:
<img src="#Html.Action("DownloadLogo", new { logoID = item.Logo.Key })" alt="" width="60" height="60">
And I have the following code in my controller:
public FileContentResult DownloadLogo(int logoID)
{
LogoDTO logoDTO = _serviceClient.GetLogo(logoID);
return File(logoDTO.LogoContent, logoDTO.LogoContentType);
}
I got the error below when reaching the code in my view:
HttpException
Error executing child request for handler 'System.Web.Mvc.HttpHandlerUtil+ServerExecuteHttpHandlerAsyncWrapper'.
Before leaving the controller I check values:
logoDTO.LogoContent = {byte[50802]}
logoDTO.LogoContentType = "image/png"
Any idea?
Thanks.

Html.Action should be Url.Action instead. Html.Action will render an tag inside your href attribute. Url.Action will only render the URL.

Related

Display message from Servlet to JSF page

I'm trying to display success message in xhtml page from servlet but no luck, here's my code
In servlet i have
FacesContextFactory contextFactory = (FacesContextFactory)FactoryFinder.getFactory(FactoryFinder.FACES_CONTEXT_FACTORY);
LifecycleFactory lifecycleFactory = (LifecycleFactory)FactoryFinder.getFactory(FactoryFinder.LIFECYCLE_FACTORY);
Lifecycle lifecycle = lifecycleFactory.getLifecycle(LifecycleFactory.DEFAULT_LIFECYCLE);
FacesContext facesContext = contextFactory.getFacesContext(request.getSession().getServletContext(), request, response, lifecycle);
facesContext.addMessage( "user:displaymessagesave", new FacesMessage("user saved successfully" ));
In xhtml page inside form i have written tag for display message form id=user
<h:message class="success" for="displaymessagesave" id="displaymessagesave" />
Saving to database is happening but its not displaying any message, please suggest where i'm going wrong.
It is not possible to access FacesContext from a servlet other than FacesServlet.
Recently I faced that same problem, and what I did was, on my servlet, put the messages in the Session:
List<String> msgs=(List<String>)request.getSession().getAttribute(KEY);
if (msgs==null)
{
msgs=new ArrayList<String>();
}
msgs.add("My new message");
request.getSession().setAttribute(KEY, msgs);
Then, on the xhtml view, I added a call to put these messages on FacesContext, and a growl element:
<h:outputText value="#{managed.prepareMessages()}"/>
<p:growl id="growl" showDetail="false" life="4000" />
Finally, the prepareMessages method takes them from session and add the messages to FacesContext:
public String prepareMessages()
{
List<String> msgs = (List<String>)FacesContext.getCurrentInstance()
.getExternalContext().getSessionMap().get(KEY);
if (msgs!=null)
{
for(String msg:msgs)
{
FacesContext.getCurrentInstance().addMessage(null,
new FacesMessage(msg));
}
FacesContext.getCurrentInstance().getExternalContext()
.getSessionMap().remove(KEY);
}
return "";
}
It may not be an elegant solution, but is the only one I found...
Don't give the same id for message as the "for" component. If you just want a messageholder without attaching it to a valueholder than you should use the tag.
<h:messages class="success" id="displaymessagesave" />

use the result of return file() of a controller as src of image tag in another view

I have a controller DisplayImage which return binary file and i can see the result in its view without any
problem,
but i want use the result of this controller in image view as a partial view but it is not possible
as when i call the html.partial(_partialview) the model which have been passed to partial , is index model
let me show my code:
public ActionResult DisplayImage(int id = 1)
{
Product product = db.Product.Find(id);
return File(product.Blob, "image/png");
}
and
public ActionResult Index()
{
return View(db.Product.ToList());
}
and in index view i wrote:
#Html.Partial("_DisplayImage")
and in partial view i wrote:
<img style="width:60px" src="#Url.Action("DislpayImage", "Product", new { id="1" })" alt="myimage" />
also if i use the img tag directly in index view still doesn't work and the result is :
<img alt="myimage" src="/Product/DislpayImage/1" style="width:60px">
without any image
so what can i do with this problem
I hope describe my problem clear
If not, please ask!
Thanks in advance!
You have a typo in your action name.
DislpayImage
is not the same as
DisplayImage
<img style="width:60px" src="#Url.Action("DisplayImage", "Product", new { id="1" })" alt="myimage" />

Ajax.BeginForm using ASP.NET MVC 3 - Nothing Happens

All I need to do is create a simple search page that displays results in a partial view. I have a search text box and a search submit button. I followed a tutorial I found online that seems very easy and quick to implement, but I am missing something here. When I click the search button nothing happens. Any ideas on what I am doing wrong or missing would be greatly appreciated.
I include the following script files in the main layout page
#Script("jquery-1.5.1.min.js")
#Script("modernizr-1.7.min.js")
#Script("jquery-ui.min.js")
#Script("jquery.unobtrusive-ajax.js")
#Script("jquery.validate.min.js")
#Script("jquery.validate.unobtrusive.min.js")
#helper Script(string scriptName)
{
<script src="#Url.Content("~/Scripts/" + scriptName)" type="text/javascript"> </script>
}
The main search view is called AdminMenu. This is listed under a Area in my project called Admin.
The following code in my main view
#using (Ajax.BeginForm("AdminSearch", "AdminMenu", new {area = "Admin"}, new AjaxOptions { HttpMethod = "GET", InsertionMode = InsertionMode.Replace, UpdateTargetId = "searchResults"}))
{
<input type="text" name="q" />
<input type="submit" value="Search"/>
}
<div id="searchResults">
</div>
Code in my partial view _adminSearch
<div id="searchResults">
<div class="entitybox">
#{
var grid = new WebGrid(
Model,
defaultSort: "Name", canPage: false
);
}
#grid.GetHtml(
tableStyle: "_tableGrid",
columns: grid.Columns
(
grid.Column("Name", "Name", item => #Html.ActionLink((string)item.Name, "SelectRecord", new { controller = "Menu", agencyKey = item.Id, name = item.Name }))
)
)
</div>
</div>
Code for the Controller
public class AdminMenuController : Controller
{
public ActionResult AdminMenu()
{
return View();
}
public PartialViewResult AdminSearch(string q)
{
Records results = AgencyBusiness.GetAdminSearch(q);
return PartialView("_adminSearch", results);
}
}
When the search button is clicked nothing happens. If you put a break point on the AdminSearch method in the controller class it never gets hit.
Thanks in advance for your time.
I think the problem is that you have a div called "searchResults" in both your main view and partial view. Ajax is probably getting confused.
You need to include the MicrosoftAjax.js file when using Ajax.BeginForm.
I solved this issue. Odd thing. I used a shared view to show the current user at the top of the view using the following line.
#RenderPage("~/Views/Shared/_LoginBar.cshtml")
The main problem was that #Ajax.BeginForm function did not output any form tags to the browser.
By using the following line instead, the form tags appeared in the HTML source and the ajax function worked.
#Html.Partial("~/Views/Shared/_LoginBar.cshtml")

Html.ActionLink in Partial View

I am using the following code in my master page:
<% Html.RenderAction("RecentArticles","Article"); %>
where the RecentArticles Action (in ArticleController) is :
[ChildActionOnly]
public ActionResult RecentArticles()
{
var viewData = articleRepository.GetRecentArticles(3);
return PartialView(viewData);
}
and the code in my RecentArticles.ascx partial view :
<li class="title"><span><%= Html.ActionLink(article.Title, "ViewArticle", new { controller = "Article", id = article.ArticleID, path = article.Path })%></span></li>
The problem is that all the links of the articles (which is built in the partial view) lead to the same url- "~/Article/ViewArticle" .
I want each title link to lead to the specific article with the parameters like I'm setting in the partial view.
Thanks.
I think your not using the ActionLink correctly. Change the ActionLink code to:
Html.ActionLink(
article.Title,
"ViewArticle",
"Article", // put the controller here
new
{
id = article.ArticleID,
path = article.Path
},
null)
Notice the null at then end.
EDIT: Why are you using [ChildActionOnly] in your controller? Since it is an MVC 2 feature I am assuming that you are using MVC2? Try removing it and check out the following article:
http://www.davidhayden.me/2009/11/htmlaction-and-htmlrenderaction-in-aspnet-mvc-2.html
I think the issue has to do with your partial not rendering. I would start by just trying to verify that your partial is rendering properly. Once you confirm that start to debug why the partial is not outputing.
I was able to solve the problem by using the following call in my RecentArticles action:
return PartialView("~/Views/Shared/Article/RecentArticles.ascx", viewData);
It seems like the partial view was not being rendered at all,
Thanks !

Problem with displaying image from DB using asp.net MVC 2

I'm having trouble with displaying image from db. I think that method for saving image is working, because I see in DB that varbinary fields have some value, and that image type is correct. Also the size of image. But when I want to display image for product i don't get anything. Just blank space.. here is my code...
public byte[] GetImage(int productID)
{
Product product = products.GetByID(productID);
byte[] imageData = product.ImageData.ToArray();
return imageData;
}
That code is in my controller. Second is code from view :
<% if (product.ImageData != null) { %>
<img src='/product/getimage/<%= Html.Encode(product.ID) %>' alt=""/>
<% } %>
I tried some solutions found here on stack overflow, and everyone do it like this, but it's working for them. I dont have any idea why images aren't displayed. When i look at source code of page at debugging i have :
<img src='/product/getimage/18' alt=""/>
I'm using .net 4.0, MVC 2, VS 2010... Thanks in advance
My guess is that you have a routing issue. If the url /product/getimage/18 should work for your action you need to have a route that looks something like this:
routes.MapRoute("ProductImage",
"product/getimage/{productID}",
new { controller = "Product", action = "GetImage", productID = "" }
);
To confirm this you should use firebug and check the "net" tab (or set a breakpoint in your action and see if it gets hit when you load the page).
I would also recommend using the build in helpers to generate your urls (then this kind of problem will never happen). Instead of src='/product/getimage/<%= Html.Encode(product.ID) %>' you can write src='<%=Url.Action("GetImage", "Product", new { productID = product.ID })%>'
I'm not much of an expert on MVC yet - but from what I can see, I think your GetImage function needs to be an Action Method inside your controller, so it'll need to return an ActionResult?
You'll probably need to set the Content-Type header in the response, too.
This guy looks like he knows what he's talking about...
http://blogs.msdn.com/miah/archive/2008/11/13/extending-mvc-returning-an-image-from-a-controller-action.aspx
Try to change you method to:
public void GetImage(int productID)
{
Product product = products.GetByID(productID);
Response.ContentType = "image/jpeg";
Response.BinaryWrite(product.ImageData.ToArray());
}
You have:
<img src='/product/getimage/18' alt=""/>
Normally i'd say an image tag looks like this:
<img src='/product/getimage/18.jpg' alt=""/>
I needed to register routes in my global.cs file like Mathias suggested.
Also i needed to modify action in my controller to this :
public FileContentResult GetImage(int productID)
{
Product product = products.GetByID(productID);
return File(product.ImageData.ToArray(), product.ImageMimeType);
}
I wish thank you all for your fast answers...

Resources