Images with razor asp.net mvc inside JS - asp.net-mvc-3

I need to dynamically insert an image in my JS code. In my Razor template I have:
#section Includes {
<script type="text/javascript">
var imgPath = "#Url.Content("~/Content/img/")";
alert(imgPath);
</script>
}
Then in my JS I have:
insertImg = "";
if (response[i].someFlag == 'Y') {
insertImg = "<img src=\"" + imgPath + "/imgToInsert.gif\" width=\"6px\" height=\"10px\" />";
}
But it doesn't work - it will not find the image. The image is stored in /Content/img folder...
What am I doing wrong? I am guessing it is because it is mapping the image from Js script..looks like I will have to hardcode it?

Alert or console.log the following to see if there are too many slashes
" + imgPath + "/imgToInsert.gif"

It might be advantageous to use the MVC TagBuilder Class to build your image tags instead of using a string concatenations. Lets you build tags dynamically and makes sure they are well-formed. Most likely your tag is not well-formed.

Related

How to use replace in wkhtmltopdf or send value to header

First question:
I want to replace a value in the header. I use --header-HTML header.html for PDF header. For example :
I want to pass 3 values to a PDF:
date
Letter_Number
letter_title
Second question:
Can I use a view for the header? I want to use a view in ASP. For example:
CustomSwitches = "--header-HTML header.cshtml "
About first question
Maybe you could use an HTML page as header, as you actually do, generate new HTML using C# code, and replacing existent HTML file content, with the one you have created, just after generating PDF using Rotativa. The other option I can see, maybe a little bit efficient, because avoids generating all HTML code using C#, is that you use javascript inside your HTML to get this values (not sure if it's completely achievable, since I ignore the origin of the values you mention).
Supposing date value is current date, you could use something like this on your HTML:
<!DOCTYPE html>
<html>
<head>
<script>
function subst() {
var currentDate = new Date();
var dd = String(currentDate.getDate()).padStart(2, '0');
var mm = String(currentDate.getMonth() + 1).padStart(2, '0');
var yyyy = currentDate.getFullYear();
currentDate = dd + '-' + mm + '-' + yyyy;
document.getElementById("dateSpan").innerHTML = currentDate;
}
</script>
</head>
<body onload="subst()">
<div>
Date: <span id="dateSpan"></span>
</div>
</body>
</html>
And on the other side, point to the HTML in custom switches command. Guessing it is located in a folder called PDF, inside Views folder, you could do:
customSwitches = " --header-html " + Server.MapPath("~/Views/PDF/header.html");
I make use of similar code for generating a footer with page number and it works like a charm.
About second question:
I use an MVC action to generate the the partial view that I use as PDF header.
Your code for the custom switches should look like this (using GenerateHeader as action name, PDF as controller and yourModel as the model to be passed to the View, on which you are supposed to store you values):
customSwitches = "--header-html " + Url.Action("GenerateHeader", "PDF", yourModel, Request.Url.Scheme);
For your PDF controller, assuming PdfHeader.cshtml is the view you want to use as PDF header, the code for the action would be as this:
public PartialViewResult GenerateHeader(YourModelType yourModel)
{
return PartialView("PDF/PdfHeader", yourModel);
}
For this PartialView references, remember to include at your controller:
usign System.Web.Mvc;
Hope this helps, if don't, please let me know.

MVCRazorTOPDf:- How to add images

I have implemented a module where i m trying to generate a PDF.PDF is generated successfully using MVCRAZORtppdf.
But now I want to add a image on PDF as well.How to add a image on PDF. And I want to add image on controller level.
Here is my solution done completely inside view:
#{
Layout = null;
var imagePath = Server.MapPath("~/Content/images");
....
}
<body>
....
<img src="#imagePath\Cert_back.bmp" />
....
</body>
If you want to set an image in Controller, I guess you can use ViewBag to set value in imagePath variable.
However, keep in mind that you can use Razor's if-then-else statement and set value dynamically in View.

Relative URL inside $ajax with asp.net mvc 3

I know one can use this function
#Url.Action("MyInfo", "Home")
to avoid the hardcoding of urls, but my $.ajax calls are in a separate .js file. Would the above still work?
From my knowledge, the #Url.Action will only work inside the Razor file. But considering that we are advised to use non-obtrusive JS, I am not quite sure how I would use the #Url.Action.
Please advise.
Would the above still work?
No.
From my knowledge, the #Url.Action will only work inside the Razor file
Your knowledge is correct.
But considering that we are advised to use non-obtrusive JS, I am not
quite sure how I would use the #Url.Action.
You could use HTML5 data-* attributes on some DOM element that you are unobtrusively enhancing (unless this element is already a <form> or an anchor in which case it already contains an url):
<div id="foo" data-url="#Url.Action("foo")">Hello</div>
and then in your separate javascript file:
$(function() {
$('#foo').click(function() {
var url = $(this).data('url');
// TODO: do something with the url
});
});
Add a function parameter for the relative paths. E.g., in your View:
<script type="text/javascript">
var path = "#Url.Action("ActionName", "ControllerName")";
someAjaxMethod(path)
</script>
and in your external js file:
function someAjaxMethod(path)
{
var data = {};
$.ajax(path, data)
}

Getting raw text using #Html.ActionLink in Razor / MVC3?

Given the following Html.ActionLink:
#Html.ActionLink(Model.dsResults.Tables[0].Rows[i]["title"].ToString(), "ItemLinkClick",
new { itemListID = #Model.dsResults.Tables[0].Rows[i]["ItemListID"], itemPosNum = i+1 }, ...
Data from the model contains HTML in the title field. However, I am unable to display the HTML encoded values. ie. underlined text shows up with the <u>....</u> around it.
I've tried Html.Raw in the text part of the ActionLink, but no go.
Any suggestions?
If you still want to use a helper to create an action link with raw HTML for the link text then I don't believe you can use Html.ActionLink. However, the answer to this stackoverflow question describes creating a helper which does this.
I would write the link HTML manually though and use the Url.Action helper which creates the URL which Html.ActionLink would have created:
<a href="#Url.Action("ItemLinkClick", new { itemListID = #Model.dsResults.Tables[0].Rows[i]["ItemListID"], itemPosNum = i+1 })">
#Html.Raw(Model.dsResults.Tables[0].Rows[i]["title"].ToString())
</a>
MVCHtmlString.Create should do the trick.
Using the actionlink below you do not need to pass html in the model. Let the css class or inline style determine how the href is decorated.
#Html.ActionLink(Model.dsResults.Tables[0].Rows[i]["title"], "ItemLinkClick", "Controller", new { #class = "underline", style="text-decoration: underline" }, null)
those are the cases that you should take the other path
#{
string title = Model.dsResults.Tables[0].Rows[i]["title"].ToString(),
aHref = String.Format("/ItemLinkClick/itemListID={0}&itemPosNum={1}...",
Model.dsResults.Tables[0].Rows[i]["ItemListID"],
i+1);
}
#Html.Raw(title)
Remember that Razor helpers, help you, but you can still do things in the HTML way.
You could also use this:
<a class='btn btn-link'
href='/Mycontroler/MyAction/" + item.ID + "'
data-ajax='true'
data-ajax-method='Get'
data-ajax-mode='InsertionMode.Replace'
data-ajax-update='#Mymodal'>My Comments</a>

CKeditor integration with FCKeditor filebrowser

I'm using CKEditor 3 and I need to integrate a cost-free filebrowser/uploader. I tried to integrate the one that comes with FCKEditor but I always get this XML error:
The server didn't send back a proper XML response. Please contact your system administrator.
XML request error: OK (200)
Requested URL: http://example.com/admin/filemanager/browser/default/?Command=GetFoldersAndFiles&Type=File&CurrentFolder=%2F&uuid=1260817820353
Response text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<html>
<head>
<title>Index of /admin/filemanager/browser/default</title>
</head>
<body>
<h1>Index of /admin/filemanager/browser/default</h1>
<table><tr><th><img src="/icons/blank.gif" alt="[ICO]"></th>
<th>Name</th>
<th>Last modified</th>
<th>Size</th>
<th>Description</th></tr>
<!-- edited for brevity -->
I'm trying to do it in this way:
<script type="text/javascript">
window.onload = function(){
CKEDITOR.config.language='es';
CKEDITOR.config.forcePasteAsPlainText = true;
CKEDITOR.config.enterMode = CKEDITOR.ENTER_DIV;
CKEDITOR.replace('ncCont',{
filebrowserBrowseUrl: 'filemanager/browser/default/browser.html',
filebrowserUploadUrl : 'filemanager/connectors/php/upload.php'
});
};
</script>
Can FCKeditor be integrated with CKEditor? If yes, how can this be done? If not, is there a free filebrowser/uploader alternative?
Wanted to piggy back off Penuel whose code helped me a lot.
add this to /filemanager/connectors/php/upload.php
// Get the CKEditor Callback
$CKEcallback = $_GET['CKEditorFuncNum'];
//modify the next line adding in the new param
FileUpload($sType, $sCurrentFolder, $sCommand, $CKEcallback);
add this to /filemanager/connectors/php/io.php
// This is the function that sends the results of the uploading process to CKE.
function SendCKEditorResults ($callback, $sFileUrl, $customMsg = '')
{
echo '<script type="text/javascript">';
$rpl = array( '\\' => '\\\\', '"' => '\\"' ) ;
echo 'window.parent.CKEDITOR.tools.callFunction("'. $callback. '","'.
strtr($sFileUrl, $rpl). '", "'. strtr( $customMsg, $rpl). '");' ;
echo '</script>';
}
modify this /filemanager/connectors/php/commands.php
//line 158
function FileUpload($resourceType, $currentFolder, $sCommand, $CKEcallback = '')
//line 166
if ( (isset($_FILES['NewFile']) && !is_null($_FILES['NewFile']['tmp_name']))
# This is for the QuickUpload tab box
or (isset($_FILES['upload']) and !is_null($_FILES['upload']['tmp_name'])))
{
global $Config ;
$oFile = isset($_FILES['NewFile']) ? $_FILES['NewFile'] : $_FILES['upload'];
...
if($CKEcallback == '')
{
// this line already exists so wrap the if block around it
SendUploadResults( $sErrorNumber, $sFileUrl, $sFileName ) ;
}
else
{
//issue the CKEditor Callback
SendCKEditorResults ($CKEcallback, $sFileUrl,
($sErrorNumber != 0
? 'Error '. $sErrorNumber. ' upload failed. '. $sErrorMsg
: 'Upload Successful'));
}
You'll need to add the upload URL's to your CKEDITOR definition like so:
var filemanager = '/js/ckeditor/filemanager/';
var browser = filemanager + 'browser/default/browser.html';
var connector = filemanager + 'connectors/php/connector.php';
var upload = filemanager + 'connectors/php/upload.php';
CKEDITOR.replace( id,
{
customConfig : this.config,
filebrowserBrowseUrl : browser +'?Connector=' + connector,
filebrowserImageBrowseUrl : browser + '?Type=Image&Connector='
+ connector,
filebrowserFlashBrowseUrl : browser + '?Type=Flash&Connector='
+ connector,
filebrowserUploadUrl : upload + '?type=Files',
filebrowserImageUploadUrl : upload + '?type=Images',
filebrowserFlashUploadUrl : upload + '?type=Flash'
});
I think that covers everything left off by Penuel
To answer your question I have posted one small tutorial on my blog with step by step instructions to integrate the File Browser of FCKEditor in CKEditor. Please goto:
http://www.mixedwaves.com/2010/02/integrating-fckeditor-filemanager-in-ckeditor/
I have done this for PHP connector but should be pretty simple for other languages as well.
You can also download the already done example or view the demo from this article.
I'm using a custom file browser with my implementation of ckeditor, so I don't see why you couldn't use the old file browser. It uses the same javascript to populate the editor.
Just install the old FCK editor in whatever directory, and make sure you have the correct path to that browser in your config. I'm guessing that you have a pathing problem above.

Resources