Is there a numeric UpDown control for ASP.NET? - html

Is there a way I can use a numeric updown in ASP.NET without using JavaScript?
And if not, is there an alternative?

I was trying to do the same thing, and it turns out the asp textbox has an option for it. what worked for me was this:
<asp:TextBox TextMode="Number" runat="server" min="0" max="20" step="1"/>
this gave me a textbox which, when mouse hovers over it or is given focus, shows the up-down controls, and only allows numbers from min to max.
it works the same as
<input type="number" min="0" max="20" step="1" />

Please look into the Ajax Control Toolkit
http://www.asp.net/ajaxLibrary/AjaxControlToolkitSampleSite/NumericUpDown/NumericUpDown.aspx
<ajaxToolkit:NumericUpDownExtender ID="NUD1" runat="server"
TargetControlID="TextBox1"
Width="100"
RefValues="January;February;March;April"
TargetButtonDownID="Button1"
TargetButtonUpID="Button2"
ServiceDownPath="WebService1.asmx"
ServiceDownMethod="PrevValue"
ServiceUpPath="WebService1.asmx"
ServiceUpMethod="NextValue"
Tag="1" />
Also consider adding the reference with NuGet by using PM> Install-Package AjaxControlToolkit

I think the following html can answer your question:
<head runat="server">
<title>Numeric Up Down</title>
<script type="text/jscript">
function Load() {
/*numericUpDown1.value = or*/ document.getElementById("numericUpDown1").value = parseFloat(document.getElementById("<%=NumericUpDown1.ClientID%>").value);
}
function Change() {
document.getElementById("<%=NumericUpDown1.ClientID%>").value = document.getElementById("numericUpDown1").value; //or numericUpDown1.value
}
</script>
</head>
<body onload="Load()">
<form id="form1" runat="server">
<div>
<input type="number" id="numericUpDown1" onchange="Change()" />
<asp:HiddenField ID="NumericUpDown1" runat="server" />
</div>
</form>
</body>
And then on the asp server side code in C# or Visual Basic, you can treat that HiddenField as NumericUpDown, but note that his value is string, and not decimal, like System.Windows.Forms.NumericUpDown control, or float, or double, or int, so you will have to Parse it to one of these types for what you need the most.
If you want to style the numeric up down, then in javascript it is simple. Just set document.getElementById("numericUpDown1").style, but if you want to do it through the asp server side code in C# or Visual Basic, then the html must be different:
<head runat="server">
<title>Numeric Up Down</title>
<script type="text/jscript">
function Change() {
document.getElementById("<%=NumericUpDown1.ClientID%>").value = document.getElementById("numericUpDown1").value; //or numericUpDown1.value
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<% this.Response.Write(string.Format("<input type='number' id='numericUpDown1' value='{0}' onchange='Change()' style='{1}' />", this.NumericUpDown1.Value, this.numericUpDown1Style)); %>
<asp:HiddenField ID="NumericUpDown1" runat="server" />
</div>
</form>
</body>
numericUpDown1Style is a protected field whose type is string defined in the asp server side code in C# or Visual Basic.
If you want to give it a class and not to style it, then the html must be:
<head runat="server">
<title>Numeric Up Down</title>
<script type="text/jscript">
function Change() {
document.getElementById("<%=NumericUpDown1.ClientID%>").value = document.getElementById("numericUpDown1").value; //or numericUpDown1.value
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<% this.Response.Write(string.Format("<input type='number' id='numericUpDown1' value='{0}' onchange='Change()' class='{1}' />", this.NumericUpDown1.Value, this.numericUpDown1CssClass)); %>
<asp:HiddenField ID="NumericUpDown1" runat="server" />
</div>
</form>
</body>
numericUpDown1CssClass is a protected field whose type is string defined in the asp server side code in C# or Visual Basic.
If you want to style it and give it a class, then html is like html #2 or html #3, but the only change is in the following line:
<% this.Response.Write(string.Format("<input type='number' id='numericUpDown1' value='{0}' onchange='Change()' style='{1}' class='{2}' />", this.NumericUpDown1.Value, this.numericUpDown1Style, this.numericUpDown1CssClass)); %>
I think you know what is numericUpDown1Style and numericUpDown1CssClass from #2 and #3
RECOMMENDED TIP:
If your website contains a lot of numeric up down controls that are used in your asp server side code, and this is disadvantageous to create all of them this way, then you can add new "Web User Control" item to your website and name it "NumericUpDown". Then in its source html you can copy the html #1 or html #2 or html #3 or html #4 that I posted above (depends on if you want to style the numeric up down or not, or give it a class or not, or both or not) with some removes and changes, because it is not "WebForm", but "Web User Control"
and in the asp server side code make the following properties (They are in C#, but if you use Visual Basic, I don't think it will be a problem for you to translate the code):
public decimal Value
{
get
{
return decimal.Parse(this.HiddenField.Value);
}
set
{
this.HiddenField.Value = value.ToString();
}
}
//Like the System.Windows.Forms.NumericUpDown.Value, but if you dislike 'decimal', and you want other type, then you can change the return type and the type Parse.
//Note that the ID of the HiddenField is simply "HiddenField", and not "NumericUpDown1", so make sure in the Source html to rename "NumericUpDown1" to "HiddenField", but probably you would like a different ID, so if you gave it different ID, then ensure that in the code you refer this HiddenField with the ID you chose, and not "HiddenField" or "NumericUpDown1".
//The following properties are for only if you want to style your Numeric Up Down:
protected string style;
public string Style
{
get
{
return this.style;
}
set
{
this.style = value;
}
}
//If you chose, copied, pasted and changed html #2 or html #4, then don't forget to replace this.numericUpDown1Style to this.Style in the source html of the Web User Control.
//Optional
public Unit Width
{
get
{
int startIndex = this.style.IndexOf("width") + 6;
if (index != -1)
{
int endIndex = this.style.IndexOf(';', startIndex);
return Unit.Parse(this.style.Substring(startIndex, endIndex - startIndex));
}
return Unit.Empty;
}
set
{
if (this.style.Contains("width"))
{
this.style = this.style.Replace("width:" + this.Width.ToString() + ';', "width:" + value.ToString() + ';');
}
else
{
this.style += "width:" + value.ToString() + ';';
}
}
}
//The same you can do with the Height property.
//You can replace all the style code with the CssClass code instead, or just add it:
protected string cssClass;
public string CssClass
{
get
{
return this.cssClass;
}
set
{
this.cssClass = value;
}
}
//If you chose, copied, pasted and changed html #3 or html #4, then don't forget to replace this.numericUpDown1CssClass to this.CssClass in the source html of the Web User Control.
If you style the NumericUpDown, so know also that in every ASP.NET control, you can type after their ID .Style["style"] = "value".
If you want to be able to do this with NumericUpDown too, then change the type of the protected field style from string to MyStyle
There is the definition of MyStyle:
public class MyStyle
{
internal string style;
public string this[string style]
{
get
{
int startIndex = this.style.IndexOf(style) + style.Length + 1;
int endIndex = this.style.IndexOf(';', startIndex);
return this.style.Substring(startIndex, endIndex - startIndex)
}
set
{
this.style = this.style.Replace(style + ':' + this[style] + ';', style + ':' + value + ';')
}
}
}
Add this class to the Code of the Web User Control, and change the Style property:
public string Styles
{
get
{
return this.style.style;
}
set
{
this.style.style = value;
}
}
and then add the property:
public MyStyle Style
{
get
{
return this.style;
}
}
and change the line from:
protected string style;
to:
protected readonly MyStyle style = new MyStyle();
Don't forget in the source html of Web User Control, to replace this.Style to this.Styles.
NOTE: I didn't had patience to test the code by myself, so it might not work, so you'll have to fix it by yourself.
At least you understood my idea.
After the fixes, you can edit my answer and replace the wrong code with your fixed code.
I will appreciate it very much!
This Web User Control is the ASP NumericUpDown you wanted!

If you are stuck on .NET 4.0 and you want to use the native HTML5 input type "number" (rather than the NumericUpDown from Ajax Control Toolkit) you can use a combination of the ASP TextBox control with extra "type" tag:
<asp:TextBox runat="server" ID="txtMyTextBox" type="number" min="0" max="10" step="1"/>
If you want to prevent any text input, you could even add a FilteredTextBoxExtender from Ajax Control Toolkit:
<ajaxToolkit:FilteredTextBoxExtender runat="server" TargetControlID="txtMyTextBox" FilterType="Numbers" />

Related

How to use runat = "server" in input tag?

I'm writing in asp.net. When I add runat="server" property to my input tag, its value is null. When I remove runat="server" it works correctly. Who knows the reason?
I want change its property from code behind, that's why I wrote runat="server". However, the value is null.
protected void btnSaveChanges_Click(object sender, EventArgs e)
{
string current_id = Session["Current_user"].ToString();
string a = Request.Form["newusername"];
string b = Request.Form["newpassword"];
string c = Request.Form["rewpassword"];
}
Code for control:
<input type="text" name="newusername" placeholder="Enter Username" required="required" runat="server"/>
When you add runat="server" and make the simple HTML control to asp.net HTML control, then asp.net renders the id and the name of that control in a manner that does not conflict with other asp.net controls on the same page.
So change the input to: (note now I add id, and remove the name!)
<input type="text" id="newusername" placeholder="Enter Username" required="required" runat="server"/>
and get the value using the post like this:
Request.Form[newusername.UniqueID]
or using the value:
newusername.value
other links to consider:
Accessing control client name and not ID in ASP.NET
Use newusername.Value to access the value of the control in your server side function.
Like
protected void btnSaveChanges_Click(object sender, EventArgs e)
{
string current_id = Session["Current_user"].ToString();
string a = newusername.Value;
string b = newpassword.Value;
string c = rewpassword.Value;
}
You can't change an HTML control's properties using c# server side code. But you can do that using several other methods -
Method 1
you can use plain javascript or jquery to alter the HTML DOM element.
Method 2
you can create the HTML elements you want dynamically using HtmlGenericControl.
HtmlGenericControl username = new HtmlGenericControl("input");
username.attr("type", "text");
username.attr("name", "newusername");
And then you can append the controls into some div, like,
Front-End HTML code where you will add your dynamic controls-
<div id="dynaHtml" runat="server"></div>
Now, you can use that div to add your dynamic controls to page -
dynaHtml.Controls.Add(username);

Dynamic pass value in a Play2 scala template

I try to dynamically change value of its variable. Once onclick (Change Ticket ID ) button then execute onClickSendEmail and variable value should be change of tickedId.
Its unable to update with newTickedId. I tried while create variable using #defining and individual calling by function also.
So, Basically I got stuck. how it will be solve.
#(sender: String)
<!--#{var tickedId = "tickedId"}-->
#defining(sender.contains("#")) {isEmail =>
#main((if(isEmail) "Email" else "Chat") + " Messages - " + sender) {
...
...
...
<div>
<a onclick="onClickSendEmail();return false;">
Change Ticket ID
</a>
</div>
#defining("getTicketId()") { tickedId =>
#views.html.common.form.panel("Reply",controllers.routes.ChatMessageController.sendEmail(tickedId,sender),"Send"){
<textarea id="emailArea" cols="100" rows="4" name="emailArea"></textarea>
}
<script type="text/javascript">
function onClickSendEmail() {
tickedId= "NewUpdatedTicketId";
}
function getTicketId() {
return "NewUpdatedTicketId";
}
</script>
}
}
}
You should not mix Twirl templating with Javascript. It's a bad approach.
The role for Twirl is to render HTML blocks. You can define conditions and variables here in order to dynamically change the HTML output. While with Javascript you can modify this rendered HTML output without reloading the page.
There are cases where you need to use a Twirl variable in Javascript, then you can do something like:
#(chartData: Html)
<script>
let jsData = #twirlData; // where twirlData is an existing variable
console.log(jsData)
</script>
Here's a link where you can read more.

ZK get value of a HTML input

I want to get a value of a HTML text input in my ViewModel :
<div class="InputAddOn"
visible="#bind(vm.resetPasswordEmailDiv)">
<h:input class="InputAddOn-field"
name="resetPasswordEmail" id="resetPasswordEmail"
disabled="#bind(vm.resetPasswordEmailDisabled)"
value="#bind(vm.resetPasswordEmail)"/>
<button class="InputAddOn-item"
onClick="#command('sendResetPasswordEmail')">
Send
</button>
</div>
So when I click on the send button I get the value in my #Command method.
Here even the value="#bind(vm.resetPasswordEmail)" dosen't work
I have copied your code and the binding worked just fine. Below you find an example that uses both the binding and the command parameter:
<div xmlns:h="xhtml" viewModel="#id('vm')#init('somePath.MyViewModel')">
<h:input value="#bind(vm.bindingParam)" />
<button label="Send" onClick="#command('doCommand', commandParam=self.previousSibling.value)" />
</div>
public class MyViewModel
{
String bindingParam;
public String getBindingParam()
{
return bindingParam;
}
public void setBindingParam(String bindingParam)
{
this.bindingParam = bindingParam;
}
#Command
public void doCommand(#BindingParam("commandParam") String commandParam)
{
System.out.println(bindingParam + " " + commandParam);
}
}
When you click the button, it will output null null or myText myText according to the content of the input.
Retrieving the text from the input is done with the same expression language as the bindings. self is the replacement for this, and I used getPreviousSibling but you should be able to use IDs, too.

HTMLService won't display return value

I created a sidebar to have a basic UI for searching my Google sheet. I'm following this tutorial exactly to make sure the first step works, except that it doesn't! I even took out the userObject part to make it simpler (honestly, because I don't know what that part does).
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<script>
function updateButton(email, button) {
button.value = 'Clicked by ' + email;
}
</script>
</head>
<body>
<input type="button" value="Not Clicked"
onclick="google.script.run
.withSuccessHandler(updateButton)
//.withUserObject(this)
.testMe()" />
<input type="button" value="Not Clicked"
onclick="google.script.run
.withSuccessHandler(updateButton)
//.withUserObject(this)
.testMe()" />
</body>
</html>
It calls this function:
function testMe() {
Logger.log("Test log.");
return ContentService.createTextOutput("Jackpot!");
}
If it matters, the HTML runs in a sidebar via onOpen as follows:
function showGradingSidebar() {
var html = HtmlService.createHtmlOutputFromFile('testSidebar')
.setSandboxMode(HtmlService.SandboxMode.IFRAME)
.setTitle('Testing Module')
.setWidth(300);
SpreadsheetApp.getUi()
.showSidebar(html);
}
When I click the button, it does nothing (that I can see). By changing various aspects, I can get it to Logger.log() a simple message but even that doesn't work reliably if I change the HTML side.
I was reading about the security restrictions that require sanitizing what the function returns, but both HtmlService.createHtmlOutput() and ContentService.createTextOutput() were also unsuccessful. Please advise.
UPDATE: Thanks to #Bryan P, I got it to work. The testMe() is simply:
return "Jackpot";
...and the HTML page looks like this:
[html, head, etc.]<body>
<input type="button" value="Ready"
onclick="google.script.run
.withSuccessHandler(updateButton)
.withUserObject(this)
.testMe()" --->
<br><div id="output">Output goes here: </div>
<br><div id="papa">Papa goes here: </div>
<br><p></p>
<script>
function updateButton(result) {
var div = document.getElementById('output')
div.innerHTML = 'It finally works!' + result;
}
</script>
</body>
</html>
I don't know how much it helped, but I did move the script tag down to the bottom of the body, fwiw, after reading this SO post.
In Chrome, if you right-click in the sidebar area >> Inspect >> in the Console it should show a message that there wasn't a valid return type after clicking on one of the buttons.
.createTextOutput(content) returns a TextOutput type (which isn't the same as just plain text type)
It's only used when you've deployed a the web app URL and some external service calls that URL. It only gets handled with doGet() too.
Did you try just return "Jackpot"; instead?
.withUserObject(this) - this refers to button element and the whole method passes it on to the successHandler(). So you can consider keeping it. Otherwise you'd have to reference the button from within the successHandler another way:
function updateButton(email) {
document.getElementById('myButton').value = 'Clicked by ' + email;
}
...which requires you add an ID attribute into the button.
You can always do:
function updateButton(email, button) {
console.log('Success hit');
button.value = 'Clicked by ' + email;
}
...to check whether the successHandler was even called in that Chrome dev console too.

Issue related to inbuilt javascript function of Telerik controls

I have asp.net webapplication having some telerik controls.
i have a RadTextBox(txtSearch) and RadButton(btnSearch) on .aspx page.
i have written following validation for empty Textbox:
$('#btnSearch').click(function () {
if ($('#txtSearch_text').val() == '') {
$('#txtSearch_text').addClass('validation');
return false;
}
else {
$('#txtSearch_text').removeClass('validation');
}
});
in validation class i have set Border-left:2px solid red
now problem is that when i click on btnSearch it sets validation class to txtSearch textbox, but when i use mouseover on txtSearch textbox class name suddenly changed to someother from inbuilt javascript function of Telerik. in this Javascript function of telerik TextBox, it changes class name of textbox to another class.
and this execution of change class occurs after executing custom javascript function.
so i want to execute customer javascript function after executing inbuilt functions of telerik. how to do it?
Thanks
You can define invalid states for RadInputs. RadTextbox by itself cannot be invalid because you can put anything in a textbox (unlike a numeric textbox, for example), yet here is a starting point:
<telerik:RadTextBox ID="RadTextBox1" runat="server">
<InvalidStyle BackColor="Red" />
</telerik:RadTextBox>
<asp:RequiredFieldValidator ID="TextBoxRequiredFieldValidator" runat="server" Display="Dynamic"
ControlToValidate="RadTextBox1" ErrorMessage="The textbox can not be empty!">
</asp:RequiredFieldValidator>
<telerik:RadButton ID="RadButton1" runat="server" OnClientClicked="test" Text="submit"
AutoPostBack="false" />
<script type="text/javascript">
function test() {
var tb = $find('RadTextBox1');
if (tb.get_value() == "") {
$find('RadTextBox1')._invalidate();
$find('RadTextBox1').updateCssClass();
}
}
</script>
Tampering directly with the HTML of complex controls may get you nowhere because they will try to update/fix their state according to the logic they have.