View an image in ASP.NET MVC 5 - asp.net

I can view an image in index file like this :
#*#Html.DisplayFor(modelItem => item.ImagePath)*#//Instead of this, I use the line below
<img src="~/Images/#item.ImagePath" height=100 width=200>
But In details file I have this :
#Html.DisplayFor(model => model.ImagePath)
How can I view the image in details file when there is a model not item? I have done several attempts but failed all of them. Thanks.

You can use custom template and dataannotations
http://msdn.microsoft.com/en-us/library/ee308450(v=VS.100).aspx
http://www.codeproject.com/Tips/720515/Custom-HTML-Helper-for-MVC-Application

The answer should be like :
<img src="~/Images/#Url.Content(Model.ImagePath)" height=100 width=200 />

This razortag string " #Html.DisplayFor(model => model.ImagePath) " is calling the DB, getting the path and then presenting the path string as its output. In the Index view " item.ImagePath " is a variable that has been populated and currently contains the path ready for output. In the Details view, there are no variables, and the ImagePath is empty because the function has not run. Well technically it ran once but since it delivered its output to the view it is again empty by the time you try to use it. To get the ImagePath as your img src call the whole function where you are placing the image and it will run again and its output will be the ImagePath used for the img src.
This also will work in the Index view as well. The codeproject.com link in the above answer provides some relevant ideas.
"<img src="#Html.DisplayFor(model => model.ImagePath)"

Related

Include specific attribute or child-element text in breadcrumb rendering

Within the author it displays a breadcrumb, and I know you can modify its display to either some other static text or localisation, but I'm wondering if it's possible to dynamically show an attribute, or execute some other context-specific xpath dynamically.
As a test I can change the breadcrumb using the localisation editor variable ${i18n()}.
cc_config.xml
<elementRenderings platform="webapp">
<render element="num" as="${i18n(test)}" annotation="${i18n(test)}"/>
translation-cc.xml
<key value="test">
<comment></comment>
<val lang="en_US">Year</val>
"Year" is actually a num element.
However, trying any other variable, even 'more static' ones like ${cf} or ${tp} simply render the variable text literally, instead of evaluating it.
cc_config.xml
<elementRenderings platform="webapp">
<render element="paragraph" as="${xpath_eval(./#eId)}" annotation="${xpath_eval(./#eId)}"/>
<render element="p" as="${tp}" annotation="${tp}"/>
(paragraphs do have an eId attribute)
As you can see, I tried using annotation; but these tooltips also simply display the variable literally.
I also fiddled and tried a bunch of xpath stuff, like #eId/.#eId//#eId, but I think there's some restriction in using the Content Completion Configuration File with respect to editor variables.
So is the thinking right but I am doing something wrong, or is it not the right way but there is some other way to affect the breadcrumb? Maybe with the schema?
The element display names in cc_config.xml file do not support most of the editor variables. Most of them, like ${cf} (current file) and ${tp} (total number of pages) don't make sense to be used when rendering the name of an element.
The xpath_eval would make sense - the display name of an element may depend on its attributes (e.g. the #id attribute), it's index in the document (e.g. 'Section 3'), etc. We have a feature request registered for this case and I added your vote to it.
As a partial workaround you can use a JS API to compute the display name of the element based on the element original name and its attributes:
goog.events.listen(workspace, sync.api.Workspace.EventType.BEFORE_EDITOR_LOADED, function(e) {
e.options.elementNameEnhancer = function(elemName, attrs) {
var displayString = elemName;
var attr = attrs['id'];
if (attr) {
displayString += ' (#' + attr.attributeValue + ')';
}
return displayString;
};
});

Undefined index stripeToken

I have a stripe checkout error in my symfony project. Here is my view that uses checkout by default :
<form action="" method="POST">
<script
src="https://checkout.stripe.com/checkout.js" class="stripe-button"
data-key="pk_test_C9N5xzeBHyGplmZwpsbyciS6"
data-amount="9999"
data-name="Demo Site"
data-description="Widget"
data-image="https://stripe.com/img/documentation/checkout/marketplace.png"
data-locale="auto"
data-zip-code="true"
data-currency="eur">
</script>
</form>
The method of my controller:
public function paiementAction(Request $request)
{
\Stripe\Stripe::setApiKey("sk_test_5W9Z1CdBKN2G46sTa2O5KI3T");
$token = $_POST['stripeToken'];
try {
$charge = \Stripe\Charge::create(array(
"amount" => 1000, // Amount in cents
"currency" => "eur",
"source" => $token,
"description" => "Example charge"
));
return $this->redirectToRoute("chk38_platform_confirmation");
} catch (\Stripe\Error\Card $e) {
// The card has been declined
return $this->redirectToRoute("chk38_platform_commande");
}
}`
Error Symfony
Thank you for your help
This issue of $_POST['stripeToken'] not being populated generally occurs when your code isn't creating a Token object via Stripe Checkout prior to running this bit of code.
I would suggest that you check your Stripe account's API logs (https://dashboard.stripe.com/test/logs/overview) and ensure that you are in fact correctly creating a Token object via Stripe Checkout prior to calling this create Charge snippet.
You may also want to read through their Checkout PHP tutorial (https://stripe.com/docs/checkout/php), to get a better understanding of how all of the pieces fit together. If you still have issues after all that, you may want to write in to their support staff via https://support.stripe.com/email since you probably don't want to discuss private account specific things in public.
This is a quick finding I just experienced. If you're using the default <form action="/directory" method="POST"> ... </form> from this stripe example page with your own endpoint make sure to specify down to the index.php file inside the directory folder.
I was getting an odd error where the token was being created but I would get directed to the PHP endpoint and it wasn't a POST event. I had an index.php file in /directory/ and I had to write the complete path not just up to /directory eg. /directory/index.php. Then it worked as expected.
I want to confirm and extend what subalublub said, in that the endpoint can simply be "/charge/" without having to use index.php there.
I ran into this issue and just using "/charge" was not passing in the $_POST values, but when changing to "/charge/" the index.php file inside that folder worked correctly.
Hope this helps someone.

Format Text File using Angularjs from Nodejs

i ma using nodejs with express to read the content of a text file using node in the backend.
when i hit the service i get the data on the front end.
Object {data: "s1:- hi thank you for calling my name is oh…↵s1:- no worries your welcome bye mam
↵s2:- bye
↵", status: 200, config: Object, statusText: "OK"}
I am able to get the text but i need to format these text based on some keywords such as s1 and s2 and add line break, bold to it on the fly and display that data using angular
First suggestion is if you have access to the file and you control the content maybe you can use Markdown and then use a directive like: angular-markdown-directive
if you can't change the contents you would have to create your own directive that will effectively find and replace those tags in the content and convert them into HTML. and then you can use ng-bind-html to render the output.
it will look something like:
angular.module('specialParse', [])
.directive('specialParse', function() {
return {
template: '<div ng-bind-html="content"></div>',
link: function(scope, element, attr) {
scope.content = attr.specialParse
.replace(/\r?\n/g, '<br />') // Replace line breaks
.replace('s1', 'something') // Special tag
.replace('s2', 'somethingElse'); // Special tag
// ..... And so on.
}
}
});
And the HTML
<div special-parse="data"></div>

Best way to retrieve image from server using ajax [duplicate]

Is it possible to reload an image with an identical file name from a server using jQuery?
For example, I have an image on a page, however, the physical image can change based on user actions. Note, this does not mean the file name changes, but the actual file itself.
ie:
User views image on default page
User uploads new image
Default image on page does not change(I assume this is due to the file name being identical, the browser uses the cached version)
Regardless of how often the code below is called, the same issue persists.
$("#myimg").attr("src", "/myimg.jpg");
In the jQuery documentation, the "load" function would be perfect if it had a default method of firing the event as opposed to binding a callback function to a successful/complete load of an element.
Any assistance is greatly appreciated.
It sounds like it's your browser caching the image (which I now notice you wrote in your question). You can force the browser to reload the image by passing an extra variable like so:
d = new Date();
$("#myimg").attr("src", "/myimg.jpg?"+d.getTime());
It's probably not the best way, but I've solved this problem in the past by simply appending a timestamp to the image URL using JavaScript:
$("#myimg").attr("src", "/myimg.jpg?timestamp=" + new Date().getTime());
Next time it loads, the timestamp is set to the current time and the URL is different, so the browser does a GET for the image instead of using the cached version.
This could be one of the two problems you mention yourself.
The server is caching the image
The jQuery does not fire or at least doesn't update the attribute
To be honest, I think it's number two. Would be a lot easier if we could see some more jQuery. But for a start, try remove the attribute first, and then set it again. Just to see if that helps:
$("#myimg").removeAttr("src").attr("src", "/myimg.jpg");
Even if this works, post some code since this is not optimal, imo :-)
with one line with no worries about hardcoding the image src into the javascript (thanks to jeerose for the ideas:
$("#myimg").attr("src", $("#myimg").attr("src")+"?timestamp=" + new Date().getTime());
To bypass caching and avoid adding infinite timestamps to the image url, strip the previous timestamp before adding a new one, this is how I've done it.
//refresh the image every 60seconds
var xyro_refresh_timer = setInterval(xyro_refresh_function, 60000);
function xyro_refresh_function(){
//refreshes an image with a .xyro_refresh class regardless of caching
//get the src attribute
source = jQuery(".xyro_refresh").attr("src");
//remove previously added timestamps
source = source.split("?", 1);//turns "image.jpg?timestamp=1234" into "image.jpg" avoiding infinitely adding new timestamps
//prep new src attribute by adding a timestamp
new_source = source + "?timestamp=" + new Date().getTime();
//alert(new_source); //you may want to alert that during developement to see if you're getting what you wanted
//set the new src attribute
jQuery(".xyro_refresh").attr("src", new_source);
}
This works great! however if you reload the src multiple times, the timestamp gets concatenated to the url too. I've modified the accepted answer to deal with that.
$('#image_reload_button').on('click', function () {
var img = $('#your_image_selector');
var src = img.attr('src');
var i = src.indexOf('?dummy=');
src = i != -1 ? src.substring(0, i) : src;
var d = new Date();
img.attr('src', src + '?dummy=' + d.getTime());
});
Have you tried resetting the image containers html. Of course if it's the browser that is caching then this wouldn't help.
function imageUploadComplete () {
$("#image_container").html("<img src='" + newImageUrl + "'>");
}
Some times actually solution like -
$("#Image").attr("src", $('#srcVal').val()+"&"+Math.floor(Math.random()*1000));
also not refresh src properly, try out this, it worked for me ->
$("#Image").attr("src", "dummy.jpg");
$("#Image").attr("src", $('#srcVal').val()+"&"+Math.floor(Math.random()*1000));
Using "#" as a delimiter might be useful
My images are kept in a "hidden" folder above "www" so that only logged users are allowed access to them. For this reason I cannot use the ordinary <img src=/somefolder/1023.jpg> but I send requests to the server like <img src=?1023> and it responds by sending back the image kept under name '1023'.
The application is used for image cropping, so after an ajax request to crop the image, it is changed as content on the server but keeps its original name. In order to see the result of the cropping, after the ajax request has been completed, the first image is removed from the DOM and a new image is inserted with the same name <img src=?1023>.
To avoid cashing I add to the request the "time" tag prepended with "#" so it becomes like <img src=?1023#1467294764124>. The server automatically filters out the hash part of the request and responds correctly by sending back my image kept as '1023'. Thus I always get the last version of the image without much server-side decoding.
Based on #kasper Taeymans' answer.
If u simply need reload image (not replace it's src with smth new), try:
$(function() {
var img = $('#img');
var refreshImg = function(img) {
// the core of answer is 2 lines below
var dummy = '?dummy=';
img.attr('src', img.attr('src').split(dummy)[0] + dummy + (new Date()).getTime());
// remove call on production
updateImgVisualizer();
};
// for display current img url in input
// for sandbox only!
var updateImgVisualizer = function() {
$('#img-url').val(img.attr('src'));
};
// bind img reload on btn click
$('.img-reloader').click(function() {
refreshImg(img);
});
// remove call on production
updateImgVisualizer();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<img id="img" src="http://dummyimage.com/628x150/">
<p>
<label>
Current url of img:
<input id="img-url" type="text" readonly style="width:500px">
</label>
</p>
<p>
<button class="img-reloader">Refresh</button>
</p>
I may have to reload the image source several times. I found a solution with Lodash that works well for me:
$("#myimg").attr('src', _.split($("#myimg").attr('src'), '?', 1)[0] + '?t=' + _.now());
An existing timestamp will be truncated and replaced with a new one.
If you need a refresh of the exact URL and your browser has the image cached, you can use AJAX and a request header to force your browser to download a new copy (even if it isn't stale yet). Here's how you'd do that:
var img = $("#myimg");
var url = img.attr("src");
$.ajax({
url: url,
headers: { "Cache-Control": "no-cache" }
}).done(function(){
// Refresh is complete, assign the image again
img.attr("src", url);
});
Nothing else worked for me because while appending a token to the query string would download the new image, it didn't invalidate the image in the cache at the old URL so future requests would continue to show the old image. The old URL is the only one sent to the browser, and the server was directing the client to cache the image for longer than it should.
If this still doesn't refresh the image for you, see if this answer helps. For more information, here is documentation on the Cache-Control request header.
In the html:
foreach (var item in images) {
<Img src="#Url.Content(item.ImageUrl+"?"+DateTime.Now)" >
}
I simply do this in html:
<script>
$(document).load(function () {
d = new Date();
$('#<%= imgpreview.ClientID %>').attr('src','');
});
</script>
And reload the image in code behind like this:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
image.Src = "/image.jpg"; //url caming from database
}
}

ASP.NET MVC: Routing errors on test server

I'm developing a ASP.NET MVC3 website for the 1st time. On my development machine everything works fine.
I bin deployed everything on our test machine. After some missing DLL issues the website seemed to work on the following url:
http://localhost/Test%20Website
But when I clicked the following link (which is created by an inline javascript because I'm using Infragistics Grid which is irrelevant for the question):
<img src=\"../Resources/Edit.png\" align=\"left \">
I get HTTP Error 404.0 - Not Found, which is logical, because the Physical Path is: C:\inetpub\wwwroot\Patient\Edit\537
While the physical Path should be: C:\inetpub\wwwroot\Test Website\Views\Patient\Edit\537 (atleast... I think... don't understand how MVC routing works exactly)
The links which are made by using the ActionLink HTML helper and such work fine by the way.
So this works:
#Html.ActionLink("About", "About", "Home")
And this works:
#Html.Partial("Search", new SearchModel())
So, my question is, how do you solve these issues?
p.s.: All the images in resources don't work either. sigh
UPDATE after an answer
I'm sorry, apparantly it is important to note that this takes place in a javascript function as a string. That's because I'm using the FormatterFunction from Infragistic's JQuery grid. Ok, this is what I've got so far:
"function(val) {return '<img src=\"../Resources/Edit.png\" align=\"left\">'; }"
The name 'val' does not exist in the current context, which is logical. But I don't know how to solve it, 'cause of my limitted knowledge of javascript/Razor/etc... Could you please help? Val in this case is by the way the value of the column it's bound to. In this case the ID of patient.
Ego4eg asked more code
It's Infragistics JQuery grid. This grid has a FormatterFunction which has a string as parameter. This string needs to be a javascript function. To give you an idea, this looks like:
#(Html.Infragistics()
.Grid(Model)
.ID("grid1")
.AutoGenerateColumns(false)
.Columns(column => {
//column.For(p => p.ID).FormatterFunction("function(val) {return '<img src=\"../Resources/Edit.png\" align=\"left\">'; }").Width("25px").HeaderText(" ");
column.For(p => p.ID).FormatterFunction("function(val) {return '<img src=\"../Resources/Edit.png\" align=\"left\">'; }").Width("25px").HeaderText(" ");
column.For(p => p.ID).FormatterFunction("function(val) {return '<img src=\"../Resources/add.png\" align=\"left\">'; }").Width("25px").HeaderText(" ");
column.For(p => p.FullName).DataType("string").HeaderText("Naam").Width("250px");
column.For(p => p.Address).DataType("string").HeaderText("Adres").Width("400px");
column.For(p => p.BSN).DataType("string").HeaderText("BSN").Width("85px");
column.For(p => p.DateOfBirthAsString).DataType("string").HeaderText("Geboortedatum").Width("85px");
column.For(p => p.GeneralPractitionerName).DataType("string").HeaderText("Huisarts");
})
Hope this helps.
It would be better to use Url.Content like:
<a href=\"#Url.Content("~/Patient/Edit/" + val)\">
Try this:
<a href ="Url.Action("Edit", "Patient", new { id = val })" />

Resources