Strange Behaviour of Response.Write() - asp.net

I am working on an ASP.NET MVC Project. In my controller I check if ModelState is valid and according to the result I assign a value to IsSucceed:
if (ModelState.IsValid)
{
ModelTutucu.modelim.IsSucceed = true;
}
return View("YaziEkle",ModelTutucu.modelim);
In my view I have a div with a "success" class. I have some text written by Response.Write() to the value of IsSucceed:
<div class="success">
#if(Model.IsSucceed) {
string success = "It is successfully saved.";
Response.Write(success);
}
</div>
The problem is that success doesn't appear in the the div. It appears at top of the page. When I do something like this:
<div class="success">Foo</div>
"Foo" appears in the div, but I cant get the same result with Response.Write, it shows strange behaviour. What is the reason of this problem? How can I solve it? Thanks in advance.

You should use the # instead of Response.Write(). Response.Write() is writing before the razor is rendered and written, so that's why it comes out on top, rather than in the middle or where it should be. Using # makes sure that the string is rendered where it should be according to the html markup.
Like:
#if (Model.IsSucceed)
{
string success = "It is successfully saved.";
#success
}

Related

show default image in razor if there is no user image

This statement is not working, i want to show default image if there is no image uploaded pls help
#if (latestrow.thumb == null)
{
<img src="~/Images/no-pic.gif"/>
}
else
{
<img src="#latestrow.thumb"/>
}
There isn't anything wrong with your code. Assuming latestrow.thumb is null, you'd receive the no-pic.gif.
My only guess is that latestrow.thumb has some value other than null. Perhaps using this would be a better approach assuming the value of thumb could be blank or null (and assuming it is a string):
#if (String.IsNullOrEmpty(latestrow.thumb))
If this doesn't work, check the model being sent to the view and see what's in that property. Chances are it's populated with some value, even perhaps a blank space.
Good luck.

Refresh issue in ASP.Net MVC4 view

I have code like below in ASP.Net MVC4. and I am using Razor engine.
#{
string sDefaultEnvironId = string.Empty;
}
<script language="javascript" type="text/javascript" >
function changeHd() {
$("#hdSelEnvironmentId").val("1");
}
</script>
<input type="button" value="ChangeHD" onclick="changeHd();" />
#Html.Hidden("hdSelEnvironmentId", sDefaultEnvironId)
The value of hidden field hdSelEnvironmentId is empty when accessing this view at first time. then it was changed to 1 after I clicked button ChangeHD.
But after I pressed F5, the value of hidden field hdSelEnvironmentId is still 1, I expected it with initial empty value instead of 1. Can anyone help me to figure it out ?I just can not understand it. I am using Firefox and Firebug, thanks.
Edit As discovered by Andreas here, you can remove this behavior by adding an attribute autocomplete=off to your input:
#Html.Hidden("hdSelEnvironmentId", sDefaultEnvironId, new { autocomplete = "off" })
This effect is not due to the cache -- it's a feature (bug?) of Firefox, that when you refresh a page, the inputs of the page do not seem to get re-loaded from the server.
try the same thing in Chrome or IE, you'll see that the value resets to empty
clear the cache in Firefox, and you'll notice the value still does not get reset.
So, I'm not sure if there's a workaround, but this issue does seem to be restricted to Firefox.
instead of setting it in
#{
string sDefaultEnvironId = string.Empty;
}
just initialize it in JavaScript.
$(document).ready(function(){
$("#hdSelEnvironmentId").val() = "";
});
function changeHd() {
$("#hdSelEnvironmentId").val() = "";
$("#hdSelEnvironmentId").val("1");
}
i think this will help.. even on page refresh as document loads again the value will be set to empty and then to 1 on button click

Using translation strings in componentlinks

I've been trying to solve this problem since this morning, and I know I'm missing something obvious here but I can't seem to find it.
We are using an XML file that is published to the server which contains translations of all the standard words, such as 'read more'. It is a page with a component that is localized in the appropriate publication.
In our Razor templates we use the following code below a plain news Summary item which in turn links to the full item.
<a tridion:href="#news.ID" class="more" ><%=DefaultLabels.TranslatedTerm(((HomePage)Page).Location, "read_more")%></a>
Thing is, the server tag works just fine, but gets resolved as
<tridion:ComponentLink runat="server" PageURI="tcm:15-407-64" ComponentURI="tcm:15-1475" TemplateURI="tcm:0-0-0" AddAnchor="false" LinkText="<%= DefaultLabels.TranslatedTerm(((HomePage)Page).Location, "read_more") %>" LinkAttributes=" class="more"" TextOnFail="true"/>
As you might notice, it gets written as plain text on the page (no surprise there because the LinkText parameter is declared as String in the first place according to the liveDocs).
If I take away the
tridion:href
in the first example, and write it as
href
It works fine, the code resolves into a translated string and it's even linked... to nothing more than the TCM ID of the component, not the right page with the full news item on it.
I've tried creating a function in Razor, tried replacing the linkText, tried setting the ComponentLink in the template itself, but to no avail. I feel that it should work with just a minor adjustment to this template's code, but I fail to see it and I've started looking at custom TBB's to handle the code.
Anyone have an idea how to resolve this?
EDIT:
Chris' answer was actually the one I was looking for in this particular situation, but I feel that I should point out that Priyank's function is something that should be regarded as such as well. So thank you both for the help, it made my life somewhat easier now!
I hope this razor function will help you lot. This is very helpful function to render the link tag from the component link or external link.
#helper RenderLink(
dynamic link, // the link to render. Handles components + internal / external links
string cssClass = null, // optional custom CSS class
string title = null // optional link text (default is the title of the component being linked to)
)
{
if(link == null)
{
return;
}
if (title == null)
{
title = link.title;
}
string classAttr = string.IsNullOrEmpty(cssClass) ? "" : " class='" + cssClass + "'";
dynamic href;
string tridionLink = "";
string targetAttr = "";
if (link.Schema.Title == "External Link")
{
href = link.link;
}
else if (link.Schema.Title == "Internal Link")
{
href = link.link;
tridionLink = "tridion:";
}
else
{
href = link;
tridionLink = "tridion:";
}
if(link.target != null)
{
targetAttr = link.target == "New window" || link.target == "Popup" ? " target='_blank'" : "";
}
<a #(tridionLink)href="#href"#classAttr#targetAttr>#title</a>
}
I would suggest not using the default templates for resolving your links, rather output the link yourself something like this:
<tridion:ComponentLink runat="server" PageURI="tcm:15-407-64"
ComponentURI="tcm:15-1475" TemplateURI="tcm:0-0-0"
AddAnchor="false" LinkAttributes=" class="more""
TextOnFail="true">
<%=DefaultLabels.TranslatedTerm(((HomePage)Page).Location, "read_more") %>
</tridionComponentLink>
Better still you might consider outputting TCDL rather than the Taglib/ServerControl

Use naming convention to apply class if label contains text

I'm new to jquery, and sorry if this question is asked before (could find exactly what I was looking for)
I would like to implement the following convetion: If I create a error label with the name '_lblError' like this:
<div>
<asp:label ID="_lblError" text="this is a error msg"/>
</div>
classA or classB would be applied to it depending on a empty string or not in the 'text' parameter of the label.
I also would like to place this code in a external js file that would be used throughout the app.
Thanks for any help!
To start with, you probably need to give the label a css class that can be used for selection:
<asp:Label Id="_lblError" Text="This is the error message"
CssClass="ThisIsWhatWeWillllWorkWith" />
This will probably output something like
<span id="ct100__lblError" class="ThisIsWhatWeWillWorkWith">
This is the error message.
</span>
You can now select the label in jQuery using the class as selector, and add class A or B depending on whether the .text() property is empty or not.
$(function() {
$('.ThisIsWhatWeWillWorkWith').each(function() {
if($(this).text() == '') { $(this).addClass('ClassA'); }
else { $(this).addClass('ClassB'); }
});
});
All code is provided as is, with no guarantees of working without modification. But you get the general idea of how to solve the problem...
EDIT: In response to your comment, here's a way to do it without adding a css class to the label. Instead of using an <asp:Label> tag for the error message, wrap a literal in a tag you hard-code on your page:
<span class="ThisIsWhatWeWillWorkWith"><asp:Literal ID="__ltlError" Text="This is the error message.</asp:Literal></span>
Another, perhaps more elegant way, would be to create your own custom label, and use that instead.
public class ErrorLabel : System.Web.UI.WebControls.Label
{
public ErrorLabel() {
this.CssClass = "ThisIsWhatWeWillWorkWith";
}
}
You then put the error message on your page with the following line:
<asp:ErrorLabel ID="__lblError" Text="This is the error message" />
Again, not sure if the above code will work as is. But again, you get the idea of what to do...
If the idea is to provide say, have different font and/or background if there is an error and display nothing if there is no text in the error label then you could make the control a literal instead of a label. The literal control does not create a control with no text (MSDN doc)

Why does document.getElementById('hyperlink_element_id') return the value of the hyperlink's href attribute?

I'm trying to grab the Web.UI.WebControls.HyperLink object itself via javascript so that I can modify its ImageUrl.
Here I'm setting the hyperlink's NavigateUrl to the my javascript function call:
lnkShowHide.NavigateUrl = String.Format(
"javascript:ShowHideElement('{0}');", lnkShowHide.ClientID
)
Here's my javascript function:
function ShowHideElement(img) {
   var ele = document.getElementById(img);
   if(ele != null) {
      // Not sure if this will change the hyperlink's ImageUrl property???
      img.src = 'smallPlus.gif';
   }
}
However, if I check the value of 'ele' after calling getElementById it prints "String.Format("javascript:ShowHideElement....." and doesn't actually get the hyperlink object itself.
Any ideas would be greatly appreciated!
Why does document.getElementById() return the value of the hyperlink's href attribute?
It doesn't. But when you “alert(element)”, alert() calls toString() on the element, and HTMLLinkElement.toString() returns the contents of the href attribute, so “alert(link)” spits out the same results as “alert(link.href)”.
(Which is a bit weird and confusing, but that's how JavaScript 1.0 worked so there's not much can be done about it now.)
I check the value of 'ele' after calling getElementById it prints "String.Format("javascript:ShowHideElement....."
That shouldn't happen with the exact example you've given... there's no way the server-side “String.Format...” code should make its way through to the client side unless you accidentally enclosed it in quotes, eg.:
lnkShowHide.NavigateUrl = "String.Format(...)";
Other problems that spring to mind are that the function changes name (ShowHideElement/ShowHideImage), and you appear to be trying to set ‘.src’ on the link element (<a>). Links don't have .src, only images do.
Anyhow, you probably don't want to do a show/hide widget like this. javascript: URLs are always the wrong thing, and your example involves a lot of nested strings inside each other which is always fragile. You could try an ‘unobtrusive scripting’ approach, generating markup like:
<div class="showhide"> blah blah blah </div>
With JavaScript to add the open/close functionality at the client side (so non-JavaScript UAs and search engines will see the whole page without hiding bits). eg.:
function ShowHider(element) {
var img= document.createElement('img');
element.parentNode.insertBefore(img, element);
function toggle() {
var show= element.style.display=='none';
element.style.display= show? 'block' : 'none';
img.src= '/images/showhide/'+(show? 'open' : 'closed')+'.gif';
img.alt= show? '-' : '+';
img.title= 'Click to '+(show? 'close' : 'open');
}
img.onclick= toggle;
toggle();
}
// Apply ShowHider to all divs with className showhide
//
var divs= document.getElementsByTagName('div');
for (var i= divs.length; i-->0;)
if (divs[i].className=='showhide')
ShowHider(divs[i]);

Resources