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)
Related
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
}
I've been looking around and have not been quite able to get a clear path to the 'angular' way of accomplishing the following. What I'm trying to achieve is displaying a tooltip with information when hovering over a link within an ng-repeat loop. Based on my research, I understood that this is part of the view, and so I should probably handle this in a directive. So, I created an attribute directive called providertooltip. The html declaration is below:
<table>
<tr id="r1" ng-repeat="doc in providers">
<td>
<a providertooltip href="#{{doc.Id}}" ng-mouseover="mouseOverDoc(doc)" ng-mouseleave="mouseLeave()">{{doc.FirstName}} {{doc.LastName}}</a>
</td>
</tr>
</table
<div id="docViewer" style="display:hidden">
<span>{{currentDoc.FirstName}} {{currentDoc.LastName}}</span>
</div>
In the module, I declare my directive, and declare my mouseOver and mouseLeave functions in the directive scope. I also 'emit' an event since this anchor is a child scope of the controller scope for the page. On the controller function (docTable ) which is passed as a controller to a router, I listen for the event. Partial implementation is seen below:
app.directive("providertooltip", function() {
return {
restrict : 'A',
link: function link(scope, element, attrs) {
//hover handler
scope.mouseOverDoc = function(doc){
scope.currentDoc = doc;
scope.$emit('onCurrentDocChange');
element.attr('title',angular.element('#docViewer').html());
element.tooltipster('show');
//docViewer
};
scope.mouseLeave = function() {
element.tooltipster('hide');
}
}
}});
function docTable(docFactory, $scope, $filter, $routeParams) {
$scope.$on('onCurrentDocChange',function(event){
$scope.currentDoc = event.targetScope.currentDoc;
event.stopPropagation();
});
}
Ok, so here is my question. All of the works as expected; Actually, the tooltip doesn't really work so if someone knows a good tooltip library that easily displays div data, please let me know. But, what I'm really confused about is the binding. I have been able to get the tooltip above to work by setting the title ( default tooltip behavior ), but I can see that the binding has not yet occured the first time I hover of a link. I assume that the onCurrentDocChange is not synchronous, so the binding occurs after the tooltip is displayed. If I hover over another link, I see the previous info because as I mentioned the binding occurs in an asynchronous fashion, i.e., calling scope.$emit('onCurrentDocChange') doesn't mean the the parent scope binds by the time the next line is called which shows the tooltip. I have to imagine that this pattern has to occur often out there. One scope does something which should trigger binding on some other part of the page, not necessarily in the same scope. Can someone validate first that the way I'm sending the data from one scope to the other is a valid? Moreover, how do we wait until something is 'bound' before affecting the view. This would be easier if I let the controller mingle with the view, but that is not correct. So, I need the controller to bind data to the scope, then I need the view to 'display a tooltip' for an element with the data. Comments?
To go the angular way correctly start your directive like:
...
directive('showonhover',function() {
return {
link : function(scope, element, attrs) {
element.parent().bind('mouseenter', function() {
element.show();
});
element.parent().bind('mouseleave', function() {
element.hide();
});
}
...
Or start with http://angular-ui.github.io/ link to go the angular-way UI. Look into the bootstrap-ui module - pure angular bootstrap widgets implemented as directives. You can get a clue how the tooltip binding implemented directly from the source of the module - https://github.com/angular-ui/bootstrap/blob/master/src/tooltip/tooltip.js
Also here is another example - (having jQuery and bootstrap scripts included) - use the ui-utils module Jquery passthrough directive ui-jq'. It allows to bind Jquery plugins ( style of $.fn ) directly as angular directive.
Here is their example for binding twitter bootstrap tooltip.
<a title="Easiest. Binding. Ever!" ui-jq="tooltip">
Hover over me for static Tooltip</a>
<a data-original-title="{{tooltip}}" ui-jq="tooltip">Fill the input for a dynamic Tooltip:</a>
<input type="text" ng-model="tooltip" placeholder="Tooltip Content">
<script>
myModule.value('uiJqConfig', {
// The Tooltip namespace
tooltip: {
// Tooltip options. This object will be used as the defaults
placement: 'right'
}
});
</script>
Also look into the official angular documentation for writing directives examples,
and have a happy coding time with Angular!
quick back story--
I am working on ASP.Net based template editor that lets authors create text templates using Javascript inserted placeholder tags that will be filled in with dynamic text when the templates are used to display the final results.
For example the author might create a template like
The word [%12#add] was generated dynamically.
The application would eventually replace the tag with a dynamic word down the road (though it's not specifically relevant to this post)
The word foo was generated dynamically.
Depending on the circumstances, the template may be created in a text input, textarea or a modified version of the Ajax Control Toolkit HTML Editor. There might be 40 or more of these editable elements on the page, so using lots of stripped down or modified HTML editors would probably bog the page down too much.
The problem is that the tags such as [%12#add] are displayed inline with the user text and the result is confusing and aesthetically gross. The goal is parse the contens of the source element and when a tags such as [%12#add] are encountered, display something prettier and less cryptic to the user such as a stylable element or image wherever tags such as [%12#add] occur. The application still needs the template text with the tags on postback.
So the user might see
The word tag placeholder was generated dynamically.
but the original template would still be the value of the text input box
The word [%12#add] was generated dynamically.
It seems HTML editors like the ACT version and FckEditor accomplish this by rendering their output in an IFrame, but rather than kill myself trying to roll a lighter specialized version myself, I thought I'd ask if anyone knows of an existing free component or approach that has already tackled this.
With good reason, I don't think S.O. allows HTML formatting, but the bold "tag placeholder" above would ideally be something like tag placeholder.
I think CKEditor might be your best bet. I recently wrote a plugin for it that kept placeholders in the editable content for chunks of content that the user couldn't edit directly. A question I asked may help, particularly the comments to the accepted answer: Update editor content immediately before save in CKEditor plug-in.
The recommendation to me was to look at how object tags (e.g. as used to embed Flash movies) are handled, and from that I was able to proceed fairly quickly. Be aware though that CKEditor is not well documented for plugin developers, so you may often have to resort to looking at the source code.
Final model solution in case someone in the same situation needs a boost.
aspx page:
<div>
<asp:TextBox runat="server" ID="txtTest" TextMode="MultiLine" CssClass="Over" />
<br />
Add CKEdit
<br />
Add Tag
<br />
<asp:Button ID="btnSubmit" runat="server" Text="Submit" onclick="btnSubmit_Click" />
</div>
<script type= "text/javascript" >
<!--
function ckTest(el) {
var tinyTool = {
toolbar:
[
['Bold', 'Italic', 'UIColor'], ['Styles', 'Format', 'Font', 'FontSize']
]
};
//Note: config.htmlEncodeOutput = true; to work with ASP.NET, see postback for decoding input
var editor = CKEDITOR.replace(el);//, tinyTool);
editor.addCss('.aux1 { background-color: #FFE0C0; border: solid 1px #17659E; }');
}
function insertTag(id, tag, display) {
var e = CKEDITOR.instances[id];
if (e) {
//Storing in comments does not work. stripped out when using insertHtml. Workaround?
//e.insertHtml("<span class='aux1'>" + display + "<!--" + tag + "--></span>");
//Kludge: fake attribute
e.insertHtml("<span class='aux1' tag='" + tag +"'>" + display + "</span> ");
}
}
-->
</script>
-->
</script>
CodeBehind:
protected void btnSubmit_Click(object sender, EventArgs e)
{
//Note: CKEditor converts single to double quotes in insertHtml
Regex regHiddenTag = new Regex(#"<span\sclass=""\w+""\stag=""(\[%[0-9]{1,2}_[TR]\])"">\w+</span>");
//Note: config.htmlEncodeOutput = true;
string encoded = txtTest.Text
.Replace("<", "<").Replace(">", ">").Replace("&", "&");
//TODO: Use AntiXss Library that I have to thwart bad HTML
string extractedTag = regHiddenTag.Match(encoded).Groups[1].Value;
//store to DB
string template = regHiddenTag.Replace(
encoded,
extractedTag);
//repopulate
string finalText = template.Replace(extractedTag, "foo");
}
Suppose I have a table like:
create table
{
id numeric(5,3),
code varchar(10)
}
I have two text boxes in my form for the two fields.
Suppose if I type 1234578 in the first text box the error has been thrown in ASP.NET because I crossed the limit.
How can I validate in JavaScript or some other way for that particular range validation?
Let's take one textbox only. Attach an 'onchange' event handler to your textbox like this:
<input type="text" onchange="handleChange(this);" />
Then declare a script for validation like this:
<script>
function handleChange(input) {
if (input.value > ..your_value_here..) alert ("Invalid input");
}
</script>
Please note that the alert pop-up used here should not be actually used. Use a more subtle reminder at a more appropriate moment. The alert here is only to make things simple.
I know that in the next version of ASP.NET we'll finally be able to set the clientids on System.Web controls without the framework doing it for us in a quasi-intelligent way e.g:
id="ctl00__loginStatus__profileButton"
Does anyone know a good method in the meantime to force the above id to something like
id="profileButton"
The main reason for this is manipulation of the clientids in jQuery when dynamically adding controls to a page. The problem I can see is changing the ids will break the Viewstate?
You have to use the ClientIDMode attribute:
<asp:xxxx ID="fileselect" runat="server" ClientIDMode="Static"/>
What I tend to do is dynamically generate javascript methods which handle this. You can do this in markup or code behind so for example:
<script language="javascript" type="text/javascript">
function doXYZ()
{
$("#" + getListBoxId()).css(...)
}
function getListBoxId()
{
return "<%=this.myListBox.ClientId>";
}
</script>
You can also build the functions in the code behind and register them.
EDIT
A couple months ago I needed to fix the id of some server controls, I managed to hack it in and I described my method here here.
Basically you need put the controls inside a naming container like a user control, and then override a couple of properties which prevents the child controls from getting their uniqueid.
The performance isn't great, but you can use this selector syntax to match messy ClientIDs:
$("[id$='_profileButton']")
That matches any element ending in _profileButton. Adding the leading underscore ensures that you're matching the desired element and not another element that ends in the substring "profileButton" (e.g. "myprofileButton").
Since it has to iterate over the entire DOM, the performance can be poor if you use it in a loop or several times at once. If you don't overuse it, the performance impact is not very significant.
Another way would be to wrap your control with a div or span with a static id, then access the control through that.
E.g.
<span id="mySpan">
<asp:TextBox id="txtTest" runat="server" />
</span>
You could then target input tags inside MySpan. (though I agree it would be nice to be able to specify a nice name, provided you could handle the naming conflicts...)
I have often run in to this "problem" while developing in asp.net webforms. In most cases I tend to use the css class of the element.
jQuery(".My .Container12")
Before starting to manipulate the id:s, perhaps that is a way you can handle it aswell? It's a simple solution.
There is another solution not mentioned which is to subclass the ASP.NET controls and force the IDs:
public class MyCheckBox : CheckBox
{
public string ForcedId { get;set; }
public override string ID
{
get
{
if (!string.IsNullOrEmpty(ForcedId))
return ForcedId;
else
return base.ID;
}
set
{
base.ID = value;
}
}
public override string ClientID
{
get
{
return ID;
}
}
}
Then use this where you know the IDs will never clash:
<mytag:MyCheckBox ForcedId="_myCheckbox" runat="server" />
If you are using lists you will need to write a ListControlAdapter, and also adapters for each type of list you're using (dropdown,checkbox,radiobutton,listbox). Alternatively cross your legs and wait for .NET 4.0.