Working With ViewState with JavaScript Altered Control - javascript

Hi I'm trying to utilize more java-script, jquery, ajax in my asp code. So for a project I built this field chooser using java-script.
<asp:ListBox ID="lb1" runat="server" Height="400px" Width="170px"></asp:ListBox>
<input type="button" id="_b_Add" value="Add >" onclick="add();" style="padding:5px; margin-left:5px; margin-top:15px; width: 131px;" />
<input type="button" id="_b_Rem" value="< Remove" onclick="remove();" style="padding:5px; margin-top: -25px; margin-left:5px; width: 131px;" />
<input type="button" value="Up" onclick="moveUp(document.getElementById('lb2'));" style="padding:5px; margin-left:5px; width: 131px;" />
<input type="button" value="Down" onclick="moveDown();" style="padding:5px; margin-left:5px; margin-top: -25px; width: 131px;" />
<asp:Button ID="_b_Reset" runat="server" Text="Reset" Width="131px"
style="padding:5px; margin-left:5px; margin-top:40px;"
onclick="_b_Reset_Click" />
<asp:Button ID="_b_Run" runat="server" Text="Run" Width="131px"
style="padding:5px; margin-left:5px; margin-top:10px;"
onclick="_b_Run_Click" />
<asp:ListBox ID="lb2" runat="server" Height="400px" Width="170px" AppendDataBoundItems="True" Enabled="False"></asp:ListBox>
and here is the important javascript:
function prom() { { $.prompt('Maximum Number of Custom Types is 14 '); } }
function add() {
var opt = document.createElement("option");
var sel = document.getElementById("lb1").selectedIndex;
if ((document.getElementById("lb1").selectedIndex) != -1 && document.getElementById("lb2").length < 14) {
document.getElementById("lb2").options.add(opt);
opt.text = (document.getElementById("lb1").options[document.getElementById("lb1").selectedIndex].text);
opt.value = (document.getElementById("lb1").value);
document.getElementById("lb1").options.remove((document.getElementById("lb1").selectedIndex));
document.getElementById("lb1").options.SelectedIndex = sel;
}
else {
prom();
}
}
function remove() {
var opt = document.createElement("option");
var sel = document.getElementById("lb2").selectedIndex;
if ((document.getElementById("lb2").selectedIndex) != -1) {
document.getElementById("lb1").options.add(opt);
opt.text = (document.getElementById("lb2").options[document.getElementById("lb2").selectedIndex].text);
opt.value = (document.getElementById("lb2").value);
}
document.getElementById("lb2").options.remove((document.getElementById("lb2").selectedIndex));
document.getElementById("lb2").options.selectedIndex = sel;
}
EDIT ***
Testing the values in lb2
foreach (var item in lb2.Items.Cast<ListItem>())
{
TextBox1.Text += (item.Value).ToString();
i++;
}
This works fine on the lb1 not but when the item have been added client side its no good.
Basically now on run the values of lb2 should be iterated and fed into my report class. However I quickly realized that the changes made by the java script to lb2 are not reflected in the viewstate when the "_b_Run_Click" event is fired. So after digging around a bit I seem to get the impression that the solution is to use a hidden field ... My question is (being a js noob) how exactly do you do that and is there an more elegant alternative ?
Thanks

Latest answer
I believe your problem is because Disabled controls are not submitted in the form post. Remove Enabled="False" from lb2 and try again.
You can prevent users from clicking on that control by onclick/onfocus and setting focus to another control. Or using a hidden box to store the values and a div to display the values.
Older answer attempt below
Are you binding in the Page_Load without if (!IsPostBack)?
This will override any values in the listbox before the button event reads them
public void Page_Load
{
lb2.DataSource = ...
lb2.DataBind();
}
If that is the problem, this will fix it.
public void Page_Load
{
if (!IsPostBack)
{
lb2.DataSource = ...
lb2.DataBind();
}
}

Related

There's no focus effect when using ajax to embed html into current page and set focus

I'm developing asp.net core and test in Edge browser(version: 96.0.1054.62).
I'm send ajax request and get the html content, then I embedded the html block into current page. After that, I set focus on the html elment in the html block. But I cannot see the focus effect when I call the setFcous function.
In general, when I set focus on one elment, it will have black border wrap it like fhe following.
The following is the code sample:
Index.cshtml
<form>
<input id="btnDelete" value="Delete" type="button" style="width: 60px" />
</form>
<div id="divInputs" style="display: none">
</div>
<script type="text/javascript">
function setFocus(elementId) {
var obj = document.getElementById(elementId);
if (isDefine(obj)) {
console.log(obj);
obj.focus();
}
}
function isDefine(obj) {
return !(obj == undefined || obj == null)
}
$(function () {
$('#btnDelete').on('click', function () {
$.get('/Home/Delete?', (data) => {
$('#divInputs').html($(data));
$('#divInputs').show();
setFocus('btnAction');
});
});
});
</script>
HomeController.cs
public IActionResult Delete()
{
return View("Delete");
}
Delete.cshtml
#{
Layout = null;
}
<div>
<input id="btnAction" class="button" type="button" value="Delete"/>
<input id="btnCancel" class="button" value="Cancel" type="button"/>
</div>
The focus is set to the button from your code. You can test it with adding the following style to your page.
<style>
input:focus {
background-color: yellow;
}
</style>

How to disable a LinkButton if Input elements do not have a value?

Like the title says, I'm trying to disable a LinkButton if certain Input elements do not have a value and enable if one of the Input elements do. I am just trying to disable the LinkButton if one of the Input elements does not hold a value for now, and this is what I have so far:
Style:
<style>
.disabled-link
{
color: Gray;
}
</style>
Javascript:
<script>
$(function() {
$('select[id$=hdnSelectedOrganisations]').change(function() {
var value = hdnSelectedOrganisations.value;
var btnGenerateReport = $('a[id$=btnGenerateReport]')
var href = btnGenerateReport.attr('href');
if (value == null) {
btnGenerateReport.attr('href', '#').attr('myCustomAttr', href).addClass('disabled-link');
}
else {
linkButton1.attr('href', linkButton1.attr('myCustomAttr')).removeClass('disabled-link');
}
});
$(document).ready(function ()
</script>
Input Element to be read:
<div id="dOrganisationSearch" class="autosuggest-wrap clearfix">
<input type="text" id="txtClientName" runat="server" class="autosuggest client data_clientname" autocomplete="off" data-required="true" placeholder="Organisation" />
<input id="hdnClientID" runat="server" type="hidden" class="data_clientid" />
<div id="client-results" class="as-results as-results--modal"></div>
<p id="pSelectedOrganisations" runat="server" style="font-weight: bold; margin-top: 10px;"></p>
<input type="hidden" id="hdnSelectedOrganisations" runat="server"/>
</div>
Button to be disabled:
<div class="autosuggest-wrap clearfix" style="text-align:center;">
<button class="clear-filters lightblue view_btn att fillWidth" style="background-color: indianred; padding-top: 12px; padding-bottom: 11px;">CLEAR ALL FILTERS</button>
<asp:LinkButton ID="btnGenerateReport" runat="server" OnClick="btnGenerateReport_Click" CssClass="lightblue view_btn att fillWidth" Text="Generate Report" />
</div>
For some reason, no matter what I try, the button just won't disable. Thanks in advance for any help!
The if condition is wrong, because HiddenField.value and TextBox.text will never be null. It is string empty by default.
you need to change the if below:
if (value == null) {
to:
if (value.trim() == "") {

.NET ClientSide RequiredFIeldValidator with Bootstrap "has-error" Class

I'm working on a legacy .NET WebForms project where the front-end is being updated with Bootstrap.
There are some .NET Validation Controls which are validating on the ClientSide, but the "has-error" class needs to be added to the parent div of the input fields to match the Bootstrap markup.
Is there an event hook or a way of extending the .NET Validators so that I can add the "has-error" class to an invalid control group and remove it when valid?
e.g: Here is my markup which works server side:
<div class="form-group <%= IIf(RequiredFieldValidator1.IsValid, "has-error", "") %>">
<label class="control-label">Test</label>
<asp:TextBox runat="server" ID="TextBox1" CssClass="form-control" />
<asp:RequiredFieldValidator runat="server" ID="RequiredFieldValidator1"
ContolToValidate="TextBox1" ErrorMessage="TextBox1 is Required!" />
</div>
I was requiring the has-feedback class on the form-group div as well as the glyphicon tick and crosses depending on whether the input was valid or not. What I have found that works in my solution is to override asp.net's client side function ValidatorUpdateDisplay (note my code utilizes jQuery although you could use native JavaScript):
var originalValidatorUpdateDisplayMethod;
if (typeof(ValidatorUpdateDisplay) == "function"
&& typeof(originalValidatorUpdateDisplayMethod) != "function") {
originalValidatorUpdateDisplayMethod = ValidatorUpdateDisplay;
// now overwrite original method
ValidatorUpdateDisplay = function (val) {
originalValidatorUpdateDisplayMethod(val); // call original method first
var parent = $("#" + val.controltovalidate).parent();
if (parent.hasClass("form-group")) {
parent.addClass("has-feedback");
parent.toggleClass("has-success", val.isvalid);
parent.toggleClass("has-error", !val.isvalid);
var glyph = parent.find("span.form-control-feedback");
if (glyph.length == 0) {
glyph = $("<span class='glyphicon form-control-feedback' />");
parent.append(glyph);
}
glyph.toggleClass("glyphicon-ok", val.isvalid);
glyph.toggleClass("glyphicon-remove", !val.isvalid);
}
}
}
This adds the bootstrap validation to fields when they change as well as when an event on a control that has causesvalidation="true" is triggered.
Note: this is only adding the validations on the client side.
You'll need to put a id on the element
<div id="div1" class="someclass">
<img ... id="image1" name="image1" />
</div>
and this is the javascript which adds a class to a <div> element
var d = document.getElementById("div1");
d.className = d.className + " otherclass";
Here is what I did:
<asp:Panel ID="pnlNumberOnly" runat="server" CssClass="form-group">
<label for="<%= tbNumberOnly.ClientID %>" class="control-label">Enter a number:</label>
<asp:TextBox ID="tbNumberOnly" runat="server" CssClass="form-control" />
<asp:RegularExpressionValidator runat="server" ID="regExpNumberOnly"
ControlToValidate="tbNumberOnly"
Display="Dynamic"
ErrorMessage="Numbers only" CssClass="control-label"
ValidationExpression="^\d+$" EnableClientScript="True"/>
</asp:Panel>
and then my js looked like this:
$(document).ready(function() {
$('#<%= tbNumberOnly.ClientID %>').change(function() {
if ($('#<%= regExpNumberOnly.ClientID %>').is(':visible')) {
$('#<%= pnlNumberOnly.ClientID %>').addClass('has-error');
} else {
$('#<%= pnlNumberOnly.ClientID %>').removeClass('has-error');
}
});
});

Trying to disable CSS buttons using ASP hidden value and javascript

I am using the ASP.NET PasswordRecovery method, and have a couple of CSS buttons to submit the form OR cancel the request.
I also grab the users email address to pass along to the successtext value of PasswordRecovery method, set the ASP hiddenvalue to success, and then try to use javascript to disable the buttons based on this value.
The problem is that this hiddenfield value seems to be set to "success" on initial page load, even though when viewing the source of the rendered page shows NO value.
There is probably a better approach to this, but I have tried several different ways, and this is successful up the point that I cant change the view state of the buttons.
<script runat="server">
protected void resetuserpassword_SendingMail(object sender, MailMessageEventArgs e)
{
e.Message.IsBodyHtml = true;
e.Message.Subject = "Password Assistance";
TextBox txtUserName = (TextBox)resetuserpassword.UserNameTemplateContainer.FindControl("UserName");
string UserEmailID = Membership.GetUser(txtUserName.Text.Trim()).Email;
resetuserpassword.SuccessText = "Password sent to ";
resetuserpassword.SuccessText += UserEmailID;
ValueHiddenField.Value = "Success";
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolderArea" Runat="Server">
<script type="text/javascript">
window.onload = disableButtons;
function disableButtons() {
var element = document.getElementById('ContentPlaceHolderArea_ValueHiddenField');
if (typeof(element) != 'undefined' && element != null) {
if (document.getElementById('ContentPlaceHolderArea_ValueHiddenField').value = 'Success') {
var submitBtnElement = document.querySelector("#submitBtn");
var cancelBtnElement = document.querySelector("#cancelBtn");
submitBtnElement.style.display = "none";
cancelBtnElement.style.display = "none";
}
}
}
function clickSubmit() {
document.getElementById("ContentPlaceHolderArea_resetuserpassword_UserNameContainerID_SubmitButton").click();
}
function clickCancel() {
window.location.replace("~/Login.aspx");
}
</script>
<asp:hiddenfield id="ValueHiddenField" value="" runat="server"/>
<asp:hiddenfield id="ValueHiddenField" value="" runat="server"/>
<asp:PasswordRecovery ID="resetuserpassword" runat="server"
MailDefinition-BodyFileName="~/ResetPasswordEmailTemplate.html"
OnSendingMail="resetuserpassword_SendingMail"
successtext="Password sent to email address on record."
Width="300px" Font-Names="Arial" Font-Size="Small" UserNameTitleText="" >
<InstructionTextStyle Font-Names="Arial" Font-Size="Small" />
<MailDefinition BodyFileName="~/ResetPasswordEmailTemplate.html"></MailDefinition>
<UserNameTemplate>
<div><asp:Label ID="UserNameLabel" runat="server" AssociatedControlID="UserName" style="display:none;"></asp:Label></div>
<div style="font: arial, verdana, sans-serif;font-size: 13px;padding-bottom: 5px;font-weight: bold;">Please Enter your Username</div>
<div><asp:TextBox ID="UserName" runat="server" style="width: 180px;"></asp:TextBox></div>
<div><asp:RequiredFieldValidator ID="UserNameRequired" runat="server" ControlToValidate="UserName" ErrorMessage="User Name is required." ToolTip="User Name is required." ValidationGroup="PasswordRecovery1">*</asp:RequiredFieldValidator></div>
<div><asp:Literal ID="FailureText" runat="server" EnableViewState="False"></asp:Literal></div>
<div style="display: inline;" ><asp:Button ID="SubmitButton" runat="server" CommandName="Submit" Text="Submit" ValidationGroup="PasswordRecovery1" style="display: none;" /></div>
</UserNameTemplate>
</asp:PasswordRecovery>
<div>
<div id="submitBtn" onclick="clickSubmit()">Submit</div>
<div id="cancelBtn" onclick="clickCancel()">Cancel</div>
</div>
</asp:Content>
Your javascript if statement is assigning the value 'Success' to the Hidden Field (single equals sign).
if (document.getElementById('ContentPlaceHolderArea_ValueHiddenField').value = 'Success') {
...
}
Change it to this (double equals sign):
if (document.getElementById('ContentPlaceHolderArea_ValueHiddenField').value == 'Success') {
...
}

JavaScript - retain "textbox2" value for it to be available after refresh/reopen page

I have 2 textboxes. After writing something in the first one and clicking the OK button the value appears in textbox2 also.
I need that value to be saved after page refresh and not be modified untill someone introduces a new value in textbox1 and hits OK again.
<html>
<head> </head>
<script type="text/javascript">
function myfunction()
{
var first = document.getElementById("textbox1").value;
var textbox2 = document.getElementById("textbox2");
textbox2.value = first;
}
</script>
<body>
<input type="text" name="textbox1" id="textbox1" />
<input type="submit" name="button" id="button1" onclick="myfunction()" value="OK" />
<br/>
Your answer is:
<input type="text" name="textbox2" id="textbox2" readonly="true"/>
</body>
</html>
As per my knowledge, you can make the "Textbox2" a server control by declaring runat="server" which would retain the value even after server hit as shown below.
<input type="text" name="textbox2" id="textbox2" readonly="true" runat="server" />
Then store it in session (in case of C#) or something similar in the server side to restore the value.
Hope this Helps!!
This should do it every time. http://jsfiddle.net/CKLAg/
first, simplify your html a bit:
<input type="text" name="textbox1" id="textbox1">
<button name="button" id="button1" onclick="myFunction();">OK</button>
<br/>Your answer is:
<input type="text" name="textbox2" id="textbox2" readonly="true">
Then, add the following functions to check for localStorage, save and load storage on demand:
Note, that you will have to use jQuery to get the document ready state and set the input element when the DOM is ready.
$('document').ready(function(){
var prevAnswer = loadStorage;
$('#textbox2').attr('value', prevAnswer);
});
function loadStorage() {
if (supports_html5_storage) {
if (localStorage.getItem('myAnswer')) {
var answer = localStorage.getItem('myAnswer');
return answer;
}
}
}
function myFunction() {
var first = document.getElementById("textbox1").value;
var textbox2 = document.getElementById("textbox2");
textbox2.value = first;
if (supports_html5_storage) {
alert('storing');
localStorage['myAnswer'] = first;
}
}
function supports_html5_storage() {
try {
return 'localStorage' in window && window['localStorage'] !== null;
} catch (e) {
return false;
}
}

Categories

Resources