Problem with multiple calls to a getImage in MVC3 Razor
I'm using Razor MVC3. I need to show images stored in the database in several views (something like change the logo of the site).
I solved it using a function that returns a FileContentResult. example:
public FileContentResult GetFile(int id)
{
govImage image = db.Image.Single(i => i.imageID == id);
return File(image.lo开发者_运维问答go, "image", image.fileName);
}
In the views, I call the function in this way:
<img id="image" src="GetFile/@ViewBag.ImageIndex" width="112" height="87" alt="Image Example" />
And in the controllers, I load the ViewBag.ImageIndex with the output of a function, just like that:
ViewBag.ImageIndex = oValid.returnUniqueIndex();
This works fine with some views but in others the GetFile function is not called (I followed the process in debug mode) even when the controller is assigning the right value in ViewBag.ImageIndex.
I lost a full day trying to find what is going on. Somebody can give me a clue?
Thanks in advance
You're using a relative URL (GetFile/@ViewBag.ImageIndex) which is relative from the current path and not the root path. This means that if your GetFile action is a member of you HomeController then your link will work not work from views generated by other controllers.
You should instead use something like:
<img id="image" src="/Controller/GetFile/@ViewBag.ImageIndex" alt="Image Example" />
Or even better:
<img id="image" src="@Url.Action("GetFile", "ControllerName", new { ViewBag.ImageIndex })" alt="Image Example" />
精彩评论