Prevent Key Event on DevExress ASP.NET MVC SpinEdit - c#

In a form, I have a spin edit control like this:
formLayoutSettings.Items.Add(i =>
{
i.FieldName = "FieldA";
i.NestedExtension().SpinEdit(s =>
{
s.Properties.MinValue = 1;
s.Properties.MaxValue = 9999999999999;
s.Properties.ValidationSettings.ErrorDisplayMode = ErrorDisplayMode.ImageWithTooltip;
s.Properties.ClientInstanceName = "seFieldA";
s.Properties.Increment = 10;
s.ShowModelErrors = true;
s.Width = Unit.Percentage(100);
s.Properties.AllowMouseWheel = false;
s.Properties.ClientSideEvents.KeyDown = "OnFieldAKeyDown"; // This is the event heandeler
});
});
And the function:
function OnFieldAKeyDown(s, e) {
if (e.htmlEvent.keyCode == 38 || e.htmlEvent.keyCode == 40) {
ASPxClientUtils.PreventEventAndBubble(e.htmlEvent); // this doesn't work
ASPxClientUtils.PreventEvent(e.htmlEvent); // this either
}
}
My aim is to prevent the spin edit control value from changing when the user presses the Up key or Down keys. When I debug this, the if test inside the OnFieldAKeyDown works but PreventEventAndBubble and PreventEvent fails miserably. Also, is there any other way to do this with jquery ??
Thanks.

AFAIK, there is a workaround to prevent a user incrementing/decrementing SpinEdit value using up/down arrow keys without using PreventEvent or PreventEventAndBubble. When there's no public method available on JS side, you can try restore SpinEdit previous value in KeyDown event handler like this:
<script type="text/javascript">
function OnFieldAKeyDown(s, e) {
if (e.htmlEvent.keyCode == 38 || e.htmlEvent.keyCode == 40) {
// check if ASPxClientSpinEdit exists
if (typeof ASPxClientSpinEdit !== "undefined") {
ASPxClientSpinEdit.prototype.OnPageOrArrowKeyDown = function() {
// when user tries either increment or decrement, it returns last value instead
if (s.GetValue() != s.lastChangedValue) {
s.SetValue(s.lastChangedValue);
}
// if spinedit's minimum & maximum values also affected, set current limit
else {
s.maxValue = ASPxClientSpinEdit.MaxValue;
s.minValue = ASPxClientSpinEdit.MinValue;
}
}
}
}
}
</script>
Combine this function with jQuery may possible, any suggestions welcome.
Reference: https://www.devexpress.com/Support/Center/Question/Details/Q254514

Related

Determine whether there are changes on a form when you click a submit button

I have a form with two textboxes. I am retrieving data from the
database to populate the boxes. When my user clicks on submit button
and the content of the 2 textboxes does not change, I dont want to go through
the code.
How do I determine when the content of the boxes changes and when it does not change?
Do I need to make some kind of comparison to what I have in memory?
public ActionResult Edit(profile objprofiler)
{
if (ModelState.IsValid)
{
//Go fetch the existing profile from the database
var currentProfile = db.Profiles.FirstOrDefault(p => p.ProfileId == objprofiler.ProfileId);
//Update the database record with the values from your model
currentProfile.City = objprofiler.City;
currentProfile.State = objprofiler.State;
//Commit to the database!
db.SaveChanges();
ViewBag.success = "Your changes have been saved";
return View(profiler);
}
}
You can compare the values with a simple if condition. Something like this:
if ((currentProfile.City != objprofiler.City) || (currentProfile.State != objprofiler.State))
{
currentProfile.City = objprofiler.City;
currentProfile.State = objprofiler.State;
db.SaveChanges();
}
Or use whatever logic you're trying to achieve, really. Whether you want to compare for each field individually, use a && instead of an ||, etc. The logic you want to implement is up to you. But you'd perform the comparison in an if statement.
Note also that you can use string.Equals() instead of just the == operator to compare strings with some more options, such as case sensitivity options and other useful things.
If the comparison gets more complex, you might also encapsulate it in the profile object itself. Perhaps by overriding .Equals(), though that has other implications when testing for equality. Maybe just a simple helper function:
public bool IsEqualTo(profile obj)
{
return this.City == obj.City
&& this.State == obj.State;
}
Then in the controller you can just use that method:
if (!currentProfile.IsEqualTo(objprofiler))
db.SaveChanges();
The way I typically handle this is by setting a 'dirty' flag any time a data change event occurs on any of the form's controls.
When the user comes to submit the form, I just check the state of the flag to see whether any changes need to be saved. This avoids having to compare all data to their previous states, which can be a nuisance if there are a lot of input controls on the form.
For example:
bool isDirty;
private void textBox_TextChanged(object sender, EventArgs e)
{
// Possible validation here
SetDirty(true);
}
private void SetDirty(bool dirty)
{
// Possible global validation here
isDirty = dirty;
}
private void Submit()
{
if(isDirty)
{
// Save logic
}
}
This approach allows you to run any global validation logic whenever any data is changed.
Caveat: If a user makes a change then reverts it, the form will still submit the data.
On the client side you can check if the value has changed by running some js to compare the elements value to its initial value. Something like this.
function hasFormChanged() {
//textboxes, textareas
var els = document.querySelectorAll('input[type="text"], textarea, input[type="number"]');
for (i = 0; i < els.length; i++) {
var el = els[i];
if (el.value !== el.defaultValue) {
return true;
}
}
//checkboxes and radios
els = document.querySelectorAll('input[type="radio"], input[type="checkbox"]');
for (i = 0; i < els.length; i++) {
var el = els[i];
if (el.checked !== el.defaultChecked) {
return true;
}
}
//select
els = document.querySelectorAll('select');
for (i = 0; i < els.length; i++) {
var el = els[i];
if (el.options[el.selectedIndex].value != '') {
if (!el.options[el.selectedIndex].defaultSelected) {
return true;
}
}
}
//if we get here then nothing must have changed
return false;
}
and it that function return true indicating that something has changed you can set a hidden form value like this
<input type="hidden" value="false" id="AnyUpdates" name="AnyUpdates"/>
to true.
Then in your controller update read that field to determine if you need to do your db stuff.

paste plain text ajax custom editor chrome issue

I used below code to paste plain text in my Ajax Custom Editor. It works fine with IE and Firefox. but chrome got screwed.
please help me!
Also, is there a way to access custom editor buttons via c# code, to apply events or get set values
Sys.Application.add_load( function ()
{
editor = $find('<%=Myeditor.ClientID%>'); // Editor's ID="myEditor"
if (editor != null) {
var editPanel = editor.get_editPanel();
editPanel.set_noPaste(true);
}
//---------------------------------------------------
if (Sys.Extended.UI.HTMLEditor.isIE) {
var designMode = Sys.Extended.UI.HTMLEditor.ActiveModeType.Design;
var designPanel = editPanel.get_modePanels()[designMode];
designPanel.captureInDesign = function (ev) {
if (ev.type == "keydown" && ev.ctrlKey && !ev.altKey) {
// key event
if (String.fromCharCode(ev.keyCode).toLowerCase() == "v") {
this._commonPaste(ev);
return false;
}
}
return true;
}
}
});

adding totals on grid not working via jquery

Not sure what i am doing wrong here but I have a webpage which has a usercontrol wrapped in an update panel. This usercontrol has a gridview with a textbox in an ItemTemplate and a textbox in a footer template. The textbox in the footertemplate is supposed to get the calculated value from a function in jquery. Below is my script to get the total but the total doesn't get calculated. Please advise what am I doing wrong here. Also, let me know if I need to provide additional information. This script is in the master page. I tested to make sure jquery is working by putting the alert after the document ready which it works. Any help would be greatly appreciated.
<script language="javascript">
var totalQuantity = 0;
$(document).ready(function() {
//alert('This is test');
$(document).on('blur', 'input[id^="MainContent_MainContent_ucProjectionSet3_upProjections"]', function() {
alert('This is test');
totalQuantity = 0;
$('input[id^="MainContent_MainContent_ucProjectionSet3_gvProjections_txtCurrentTime_"]').each(function(index) {
doTotalCal($(this).attr("id"));
});
});
function doTotalCalc(_id) {
var indexVal = _id.Replace("MainContent_MainContent_ucProjectionSet3_gvProjections_txtCurrentTime_", "");
console.log(indexVal);
var strTotalQuantity = $('input[id^="MainContent_MainContent_ucProjectionSet3_gvProjections_txtCurrentTime_' + indexVal + '"]').val().replace("$", "");
totalQuantity += Number(strTotalQuantity);
}
$("#MainContent_MainContent_ucProjectionSet3_gvProjections_lblCurrentTimeTotal").html(totalQuantity);
});
</script>
I was able to accomplish this without using update panel. I didn't need to have an asynchronous postback for this project, so removing it was a fine option in making the jquery to work.
<script type="text/javascript">
$(document).ready(function() {
$("[id*=gvProjections]input[type=text][id*=txtCurrentTime]").keyup(function(e) {
GrossTotal();
});
});
var gross;
function GrossTotal() {
gross = 0;
$("[id*=gvProjections]input[type=text][id*=txtCurrentTime]").each(function(index, item) {
gross = gross + Number($(item).val());
});
$("[id*=gvProjections][id*=lblCurrentTimeTotal]").text(gross);
}
function isNumberDecimalKey(evt) {
var charCode = (evt.which) ? evt.which : event.keyCode;
if (charCode == 46) //decimal
return true
else if (charCode > 57 || (charCode > 31 && charCode < 48))
return false;
else
return true;
}

How to handle keydown Event in asp.net Textbox?

I have a textbox in web form(asp.net). when user already keyin data, then they will press Enter key, so that the data will be update to database.
Is there any way possible to perform this?
function InitTextBox() {
//var _txt = $('#<%= txt.ClientID%>'); or
var _txt = $('input:[id*="txtId"]');
if (_txt.length < 1) return;
_txt.get(0).autocomplete = 'off';
_txt.on('keydown', function (evt) {
var _self = $(this);
event = evt ? evt : window.event;
if (event.keyCode == 13) {
if ($.browser.msie)
{ event.cancelBubble = true; event.returnValue = false; }
else { event.preventDefault(); }
if (_self.val().length > 0 && _self.val().match(/^\s*$/) == null)
__doPostBack(_self.attr('name'), '');
}
});
}
Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(InitTextBox);
And set autopostback for textbox to false, please
Dino Esposito had wrote about this a while back. You wouldn't necessarily need a custom control, but can use his JavaScript.
If you have a control wrapped around a Panel, and you have the DefaultButtonID property set, the panel will trigger a postback on enter too by clicking the desired button specified by the ID. That's another way.

trouble wih validation inside of asp wizard

I have a group of 5 textboxes and I am using an asp:wizard. I want to check to see if all of the textboxes are empty I want to fire a label named lblItemBlock. Nothing I have tried has worked so far and so i tried cutting it down even smaller to test. I made the label visible on the page and on the active step tried to set the visible property to false. and for whatever reason it does not work
here is what I have:
protected void OnActiveStepChanged(object sender, EventArgs e)
{
if (Wizard1.ActiveStepIndex == Wizard1.WizardSteps.IndexOf(this.WizardStep3))
{
lblItemBlock.Visible = false;
}
}
Use the textbox/input validator in asp.net
Use a custom validator with client side script. There is probably a better method with 5 inputs but I use this when I need to validate multiple inputs in unison. The following checks that at least one of the text boxes has content:
function searchValidate(oSrc, args) {
var fName = document.getElementById('<%= txtFName.ClientID %>').value;
var mName = document.getElementById('<%= txtMName.ClientID %>').value;
var lName = document.getElementById('<%= txtName.ClientID %>').value;
if (fName == "" && mName == "" && lName == "") {
args.IsValid = false;
} else {
args.IsValid = true;
}
}

Categories