How to display this image in an ASP.NET MVC project?
I've tried this, but it wouldn't work:
<img src="C:\BBBB\1.png" />
Any brilliant suggestion, please?
Thanks a lot!
I did something similar to this to display payroll stubs. I didn't want them accessible from within wwwroot.
See this article for serving an image from an mvc action.
ASP.NET MVC3: Image loading through controller
public ActionResult ShowImage(id)
{
var file = #"C:\BBB\"+id;
var ext = file.Split('.').Last();
return File(file, "image/"+ext, Path.GetFileName(file));
}
Call it like this:
<img src="#Url.Action("ShowImage",new { id="1.png" })" alt="1.png"/>
For a loop, you could do something like this in your existing view:
for (var i = 1; i < 10; i++ ) {
#Html.Partial("ShowIfExists", new {id=i.ToString()+".png" })
}
Create a new Razor View called _ShowIfExists.cshtml
<img src="#Url.Action("ShowImage",new { id=Model })" alt="1.png"/>
And add a corresponding action:
public ActionResult ShowIfExists(id)
if ( System.IO.File.Exists(#"C:\BBB\"+id) )
return PartialView("_ShowIfExists",null,id);
}
return new EmptyResult();
}
The image tag's src needs to point to where the image resides on a web server.
<img src="http://myserver.com/myimage.png" />
You need to reference images with relative address like this: ../images/1.png.
check this tutorial to start: W3schools Html Tutorial/img Tag
If you insist on displaying a local image, you should include the protocol, which in this case is file://:
<img src="file://C:/BBBB/1.png" />
This is not a good idea for real projects tho.
Related
This is probably a very simple problem, but I am extremely new to C# / MVC and I have been handed a broken project to fix. So it's time to sink or swim!
I have an array of strings that is being passed from a function to the front end.
The array looks something like
reports = Directory.GetFiles(#"~\Reports\");
On the front end, I would like it to display each report, but I am not sure how to do that.
This project is using a MVC, and I believe the view is called "Razor View"? I know that it's using an HTML helper.
In essence, I need something like
#HTML.DisplayTextFor(Model.report [And then print every report in the array]);
I hope that makes sense.
If you want to display the file name array you can simply use a foreach:
#foreach(var report in Model.Reports){ #report }
Note that you should add the Reports property to your view model:
public class SampleViewModel
{
public string [] Reports { get; set; }
}
You could use ViewData or TempData but I find that using the view model is the better way.
You can then populate it:
[HttpGet]
public ActionResult Index()
{
var model = new SampleViewModel(){ Reports = Directory.GetFiles(#"~\Reports\")};
return View(model);
}
And use it in the view as you see fit.
Here is a simple online example: https://dotnetfiddle.net/5WmX5M
If you'd like to add a null check at the view level you can:
#if(Model.Reports != null)
{
foreach(var report in Model.Reports){ #report <br> }
}
else
{
<span> No files found </span>
}
https://dotnetfiddle.net/melMLW
This is never a bad idea, although in this case GetFiles will return an empty list if no files can be found, and I assume a possible IOException is being handled.
I have a PartialView (_Letra) that receives information from a Controller named Music ... this way
public ActionResult CarregarLetra(string id, string artista, string musica)
{
return PartialView("_Letra", ArtMus(artista, musica));
}
public ResultLetra ArtMus(string artista, string musica)
{
//Conteúdo do metodo[..]
var queryResult = client.Execute<ResultLetra>(request).Data;
return queryResult;
}
Until then, no problem. What happens is that now I need to pass other information to this same PartialView (_Letra). This information is in PartialView (_Cifra).
So I added the following lines in my Music controller
public ActionResult CarregarCifra(string id, string artista, string musica)
{
return PartialView("_Cifra", GetCifra(artista, musica));
}
public ResultChords GetCifra(string artista, string musica)
{
var cfrTest= new Cifra();
var cifra = new ResultChords();
cifra.chords = cfrTest.GetInfs(artista, musica);
return cifra;
}
Everything working so far, PartialView _Cifra receives the information
I searched and found that I could use in PartialView _Letra the Html.Partial to load my PartialView _Cifra, I did this way then
I added
<div class="item">
<div class="text-carousel carousel-content">
<div>
#Html.Partial("_Cifra", new letero.mus.Infra.Models.ResultChords());
</div>
</div>
</div>
Now it starts to complicate why, the return of this is null, I believe it is due to a new instance of ResultChords that I make in Html.Partial
I have already tried using a ViewBag also to transpose the information between Partials, but probably not correctly, due to the return being null as well.
I've already done a lot of research and I'm not getting the information I need for PartialView _Letra.
There is a better way not to use Html.Partial, or to use it properly, as I am not aware.
In _Letra use
#Html.Action("CarregarCifra", "Music", new { id=Model.Id, artista=Model.Artista, musica=Model.Musica });
if the variables are available on the model then you can pass them in; otherwise, make use of the Viewbag and set them in CarregarLetra
Are you always passing a new object to the second partial? You could just create it at the top of the new _Cifra partial.
_Cifra.cshtml
#{
var resultChords = new letero.mus.Infra.Models.ResultChords();
}
I'm attempting to write a Page Class for Links within the Header of the website I'm testing. I have the following link structure below
<ul>
<li>Home</li>
<li>About Us </li>
<li>Account</li>
<li>Orders</li>
<li>Administration Portal</li>
</ul>
What I want to do is store these into a List, then when a user select one of the links, it will take then to the page they should go to.
I have started with the following code below
List<IWebElement> headerElements = new List<IWebElement>();
headerElements.Add(WebDriver.FindElement(By.LinkText("Home")));
headerElements.Add(WebDriver.FindElement(By.LinkText("About Us")));
headerElements.Add(WebDriver.FindElement(By.LinkText("Account")));
headerElements.Add(WebDriver.FindElement(By.LinkText("Orders")));
headerElements.Add(WebDriver.FindElement(By.LinkText("Administration Portal")));
headerElements.Add(WebDriver.FindElement(By.LinkText("Log in / Register")));
headerElements.Add(WebDriver.FindElement(By.LinkText("Log off")));
I was thinking for using a for loop to do this, would this be the best way. I'm trying to avoid writting methods like the one below for each link
public void SelectCreateNewReferralLink()
{
var selectAboutUsLink = ( new WebDriverWait(WebDriver, new TimeSpan(50))).Until
(ExpectedConditions.ElementExists(By.CssSelector("#main > a:nth-of-type(1)")));
selectCreateNewReferralLink.Click();
}
I'm using C#, with WebDriver attempting to write this
Any Help would be great
Thanks
Chris
You could have a method that knows the root of the list (the ul element) and takes the title (string or enum) as a parameter.
Something like (in pseudo-java code):
selectLink(String title) {
driver.findElement(By.cssSelector("ul li a[title='" + title + "']").click();
}
In my MVC(4) application, I'm fetching the image files from the local directory and displaying it in the browser.
I've a model to store the details,and a controller to get the files and a view to display them.
Model
public class ImageModel
{
List<string> _images = new List<string>();
public ImageModel()
{
_images = new List<string>();
}
public List<string> Images
{
get { return _images; }
set { _images = value; }
}
}
Controller
public ActionResult Index()
{
var imageFiles = new ImageModel();
imageFiles.Images.AddRange(Directory.GetFiles(#"c:\mypath"));
return View(imageFiles);
}
View
#for (int imgIndex = 0; imgIndex < Model.Images.Count; imgIndex++)
{
<div >
<img src = #Model.Images[imgIndex] alt="Image" />
</div>
}
But I can not view the images in the browser, its showing empty boxes with alt.
What did I miss here? Should I create a virtual directory instead of physical location.
First, local files require the file:// URI scheme. You seem to use the native file path as img src.
But the browser security model forbids the use of local source from inside a page served by a web server (http://, https:// protocols).
To fix your situation, the implement a controller that take the desired image file name as parameter, and serve its content using the File() action.
The problem is your path names. This might help:
Controller:
public ActionResult Index()
{
var imageFiles = new ImageModel();
imageFiles.Images.AddRange(System.IO.Directory.GetFiles(#"C:\wherever\files\are\"));
for (int i = 0; i < imageFiles.Images.Count; i++)
{
// get rid of the fully qualified path name
imageFiles.Images[i] = imageFiles.Images[i].Replace(#"C:\wherever\files\are\", "");
// change the slashes for web
imageFiles.Images[i] = imageFiles.Images[i].Replace('\\','/');
}
return View(imageFiles);
}
View:
#for (int imgIndex = 0; imgIndex < Model.Images.Count; imgIndex++)
{
<div >
<img src = "#Model.Images[imgIndex]" /> <!-- put the file in quotes -->
</div>
}
looking at the code snippet, it seems to me that you forgot to surround the path with quotes
<img src = "#Model.Images[imgIndex]" alt="Image" />
but looking at the overall code, i would recommend to use relative paths.
UPD:
For a more detailed explanation, i would recomentd this blog post
I have the following image which is rendered this way.
<img src="../../../..#Model.FloorPlan.Floor_Plan_Image_Path#Model.FloorPlan.Floor_Plan_Image_Filename" alt=""/>
I want if possible it's src attribute will be changed into Url.Content.
What I have tried is this but my problem is it treats my model as string:
<img src="#Url.Content("~/Model.FloorPlan.Floor_Plan_Image_Path#Model.FloorPlan.Floor_Plan_Image_Filename")" alt=""/>
Can anyone help me?
The value of the Path and Filename is as follows:
Model.FloorPlan.Floor_Plan_Image_Path = "/Content/Uploads/FloorPlans/00004601/"
Model.FloorPlan.Floor_Plan_Image_Filename = "testfloorplan.png"
I found myself in a situation where I would need to format the string almost on any view,
so I made an extension method for this, just to get rid of those String.Format's on every View.
public static class UrlHelpers
{
public static string Content(this UrlHelper urlHelper,
string formatPath,
params object[] args)
{
return urlHelper.Content(String.Format(formatPath, args));
}
}
It just simply formats the specified path, nothing much going on, however calling it would be a bit nicer to read.
#{
var path = Model.FloorPlan.Floor_Plan_Image_Path;
var imageName = Model.FloorPlan.Floor_Plan_Image_Filename;
}
<img src="#Url.Content("~{0}{1}", path, imageName)"/>
I think I understand what you're going for. Try this:
<img src="#Url.Content(String.Format("~{0}{1}", Model.FloorPlan.Floor_Plan_Image_Path, Model.FloorPlan.Floor_Plan_Image_Filename))" alt=""/>
Try
<img src="#Url.Content("~/" + Model.FloorPlan.Floor_Plan_Image_Path + Model.FloorPlan.Floor_Plan_Image_Filename)" alt="" />