How to display Image from database in Html Helper Web Grid of [MVC 3.0 Razor] - webgrid

I am working on Web Grid HTMl helper.I want to display data from database.I succeed in displaying two columns from database but dont know hoe to display image from database.I have made the Html helper to display image in database but how to use in web grid HTML helper.
so pls help.

You could create an action that returns an image, then just use the url to it in your image tag:
<img src="/Images/View/123" />
Your action would be something like:
public ActionResult View(string id)
{
return base.File("C:\Path\File", "image/jpeg");
}

I created a small mvc3 app showing the list of Tennis Finalists with a nationality flag next to each player:
For this I used a simple Helper Class:
using System.Web.Mvc;
namespace MvcTennis.Helpers
{
public static class HtmlHelpers
{
public static MvcHtmlString CountryFlag(this HtmlHelper helper, string CountryCode)
{
string sRoot = "~/Content/Images/";
string sFlagPath = sRoot + CountryCode.ToLower() + ".png";
string image = "<img src=\"" + UrlHelper.GenerateContentUrl(sFlagPath, helper.ViewContext.HttpContext ) + "\" width=\"20px;\" border=\"1\" margin=\"0\" >";
MvcHtmlString sHtml = new MvcHtmlString(image);
return sHtml;
}
}
}
The Content/Images folder contains the flag files in .png format.
On the view page (Index.cshtml) we need to add the using directive :
Html/Razor Syntax:

Related

Display string in xml format in browser either using view or controller

I have a string in my model.The string is actually XML content. I have a link on my page, when clicked it opens a new tab and displays the text as XML.
The result should be the same as when I right click on an xml file and open with Internet Explorer. The difference is that this is no file, its text that I need to display as XML in a new tab.
Anyone have an idea how to achieve this without creating a file and without giving a path to a file.
You could have a controller that will serve this XML and set the proper content type header:
public class MyXMLController: Controller
{
public ActionResult Index()
{
MyModel model = GetModelFromSomewhere(...);
return Content(model.StringPropertyContainingXML, "text/xml");
}
}
now all that's left is to write an anchor link pointing to /myxml/index:
#Html.ActionLink("Click to open XML", "index", "myxml", null, new { _target = "blank" })

Provide static file download at server in web application

I am working on an MVC 4 web application. On one page I am providing an anchor link which refers to a file on application's directory. The code of the same is -
#Html.Action("Download_Static_File", "Charge_Entry", new { File_Path = "../../Content/Templates/Pt_Data/Pt_Data.xls", File_Name = "Pt_Data_Template", value = "Download template" });
My motive is that the file should be downloaded on click.
However when I click the link, I get an error like
Could not find a part of the path 'C:\Program Files\Common Files\Microsoft Shared\Content\Templates\Pt_Data\Pt_Data.xls'.'
I also tried
System.Web.HttpContext.Current.Server.MapPath
which is giving this error:
OutputStream is not available when a custom TextWriter is used.
The action method being called is:
public FileResult Download_Static_File(string File_Path,string File_Name)
{
byte[] fileBytes = System.IO.File.ReadAllBytes(File_Path);
return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, File_Name);
}
Is it the correct approach? Any help will be appreciated.
I also referred this link
Your anchor seem to be pointing to a controller action named Download_Static_File (which unfortunately you haven't shown) and passing a parameter called File_Path.
The #Html.Action helper that you are using in your view is attempting to execute the specified action as a child action. You may find the following blog post useful which describes child actions: http://haacked.com/archive/2009/11/18/aspnetmvc2-render-action.aspx/
I guess that what you are trying to achieve is to generate an anchor in your view pointing to the static file which can be downloaded by the user. In this case you'd rather use an anchor tag in conjunction with the Url.Action helper:
<a href="#Url.Content("~/Content/Templates/Pt_Data/Pt_Data.xls")">
Download_Static_File
</a>
This assumes that your web application has a folder called Content/Templates/Pt_Data under the root containing a file named Pt_Data.xls which will be downloaded by the user when he clicks upon this anchor tag.
If on the other hand the file that you want to be downloaded by the user is situated in a folder which is not publicly accessible from the client (for example the ~/App_Data folder) you might in this case have a controller action on your server that will stream the file:
public ActionResult DownloadStaticFile(string filename)
{
string path = Server.MapPath("~/App_Data");
string file = Path.Combine(path, filename);
file = Path.GetFullPath(file);
if (!file.StartsWith(path))
{
throw new HttpException(403, "Forbidden");
}
return File(file, "application/pdf");
}
and then in your view you would have an anchor to this controller action:
#Html.ActionLink(
linkText: "Download template",
actionName: "DownloadStaticFile",
controllerName: "Charge_Entry",
routeValues: new { filename = "Pt_Data.xls" },
htmlAttributes: null
)

Sitecore MVC Custom Link

I am trying to create a custom link from sitecore into my view
#Html.Sitecore().Field("CTA display", Model.Item, new { text = "<span>" + + "</span>"})
I am not 100% sure what the correct way to do this is, but I want to wrap the text from the link into a for styling. I've tried to put the Model.Rendering.Item.Fields["CTA display"] into there with .Text and it doesn't work.
Any help would be appreciated.
First, I'd start by creating a SitecoreHelper extension method that allows you to modify the inner html of the element you're rendering:
public static HtmlString Field(this SitecoreHelper helper, string fieldName, Item item, object parameters, string innerHtml)
{
if (helper == null)
{
throw new ArgumentNullException("helper");
}
if (innerHtml.IsNullOrEmpty())
{
return helper.Field(fieldName, item, parameters);
}
return new HtmlString(helper.BeginField(fieldName, item, parameters).ToString() + innerHtml + helper.EndField().ToString());
}
This will allow you to pass an optional innerHtml string that will be inserted between opening and closing tags of your element (in this case, an <a> tag).
From here, pass your html string containing your CTA label to the above method, or modify the method to output the field's Text value wrapped in a <span>.
I used the solution posted above by computerjules which worked a treat. You can then called the extended method like follows
#Html.Sitecore().Field("Link", Html.Sitecore().CurrentItem, new {Class = "some-class"}, "<span class='some-other-class'></span>")
and the span is rendered within the anchor tabs

How to Display Image Produced from byte in MVC 4

I'm new to MVC and I'm stuck with a problem I need to display an image which is stored in database as byte in my MVC 4 application I know how to produce the image from the byte but I dont know how to display it in the App. how can I solve this
If you want to display the image directly from the db, you need a controller that delivers the image and call that controller in the view. This posts shows how to do it:
Display image from database in _layout in mvc4
Cheers,
Rob
If you have the FileData as a byte[] and the mime type as a string, then try this controller method:
public FileContentResult Get(Guid fileId)
{
var file = _fileService.GetFile(fileId);
if (file != null)
{
return File(file.FileData, file.MimeType);
}
else
{
// Return 1x1px transparent png (67 bytes) - This is a clever trick of mine to serve an empty image without reading it from the disk. You may not want to do this!
return File(Convert.FromBase64String("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAACklEQVR4nGMAAQAABQABDQottAAAAABJRU5ErkJggg=="), "image/png");
}
}
Then in your view you need the URL to the image, which is obtained by doing this:
<img src="#Url.Action("Get", new {fileId = item.ID})" />

Display Image From Database in .rdlc report

I have one simple report in which I display company information.
In my sql database I have a CompanyMaster table in which i have one column Company Logo. In that column I only store the path of the company logo image.
Now i want to display company logo in report with company information,
How do I do this?
You could use Image control in rdlc file. Common approach is to write an Webservice that returns the Image content. So your Image URL will point to web service URL.
You webserivce class needs to inherit ImageHandler as follows:
<%# WebHandler Language="C#" Class="ServeImage" %>
using System;
using System.Web;
using System.Drawing.Imaging;
using Microsoft.Web;
using MyControllers;
public class ServeImage : ImageHandler {
public ServeImage()
{
}
public override ImageInfo GenerateImage(System.Collections.Specialized.NameValueCollection parameters)
{
ImageInfo retVal = null;
if (parameters["ID"] != null)
{
MyController myCntl = new MyController();
// myCntl.GetImageFromDB returns the binary[] content from database
retVal = new ImageInfo(myCntl.GetImageFromDB(parameters["ID"]));
}
return retVal;
}
}
Ok.. I think, I should be sorry for making you click on to an another page. Time for steps.
1.) EnableExternaImages= true for your sample report.
2.) Insert an image in your Report. Set the image source as external.
3.) Enter the expression in "use this image".
4.) Enter the value of your image file link that is saved in Database eg . of such expression is : "file:/// " + First(Fields!Imagelink.Value, "DataSet1") + ".jpeg"
5.) Important thing is that your Imagelink value must be the complete path to that image.
Note use "file:///" before the link.
6.) Any more issue please comeback and ask again. :-)
1- Create Text Parameter
2- Add Image Control to the Report
3- Set the Image to be External external and set "Use this image" to be the
parameter: [#ParameterName].
4- Finally Set the Parameter Value in Code behind before loading the report.
Setting image source in RDLC report dynamically