This blog is useful to all my friends who are working on the .Net Technology and wants to enhance their skills as well their problem solving ability.

Tuesday, June 18, 2013

Alert for unsaved changes in form Using JQUERY

var unsaved = false;

$(":input").change(function(){ //trigers change in all input fields including text type
    unsaved = true;
});

function unloadPage(){ 
    if(unsaved){
        return "You have unsaved changes on this page. Do you want to leave this page and discard your changes or stay on this page?";
    }
}

window.onbeforeunload = unloadPage;

Thursday, April 25, 2013

Adding your Custom validation in MVC 4 using Validation Attribute and unobtrusive Jquery library


1)  DEFINED YOUR PROPERTY IN MODEL CLASS ....

//DefaultReorderQuantity
        [Display(Name = "DefaultReorderQuantity", ResourceType = typeof(ResItemMaster))]
        [RegularExpression(@"^[0-9\.]*$", ErrorMessageResourceName = "InvalidValue", ErrorMessageResourceType = typeof(ResMessage))]
        [Required(ErrorMessageResourceName = "Required", ErrorMessageResourceType = typeof(ResMessage))]
        [DefaultReorderQuantityCheck("MaximumQuantity", ErrorMessage = "Default Reorder quantity must be less then Maximum quantity")]
        public System.Double DefaultReorderQuantity { get; set; }

 2) IN MODEL CREATE NEW CLASS WITH SAME NAME OF PROPERTY

[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false)]
public class DefaultReorderQuantityCheckAttribute : ValidationAttribute, IClientValidatable
{
    private readonly string _MaxQTYFieldName;
    public DefaultReorderQuantityCheckAttribute(string MaxQtyFieldName)
    {
        _MaxQTYFieldName = MaxQtyFieldName;
    }
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        var property = validationContext.ObjectType.GetProperty(_MaxQTYFieldName);
        var otherPropertyValue = property.GetValue(validationContext.ObjectInstance, null);
        if (value != null)
        {
            double DefReQTY = (double)value;
            if (DefReQTY >= (double)otherPropertyValue)
            {
                ValidationResult Ok = new ValidationResult("Default Reorder quantity must be less then Maximum quantity");
                return Ok;
            }
        }
        return ValidationResult.Success;
    }
    public IEnumerable
           GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        yield return new ModelClientValidationRule
        {
            ErrorMessage = ErrorMessage,
            ValidationType = "defaultreorderquantity"
        };
    }
}



3)  IN YOUR VIEW ADD THIS LINES TO CHECK VALIDATION FROM CLIENT SIDE

$("form").submit(function (e) {
        $.validator.unobtrusive.parse("#frmItemMaster");
       
        if ($(this).valid()) {
                   }
        e.preventDefault();
    });   


4) ADD BELOW LINES TO ADD THE RULE OF VALIDATION IN unobtrusive  VALIDATION LIBRARY ....

jQuery.validator.addMethod('defaultreorderquantity', function (value, element, params) {
            if (parseInt(element.form.DefaultReorderQuantity.value == '' ? 0 : element.form.DefaultReorderQuantity.value, 10) >= parseInt(element.form.MaximumQuantity.value == '' ? 0 : element.form.MaximumQuantity.value, 10))
                return false;
            else
                return true;
        }, '');
        jQuery.validator.unobtrusive.adapters.add('defaultreorderquantity', {}, function (options) {
            options.rules['defaultreorderquantity'] = true;
            options.messages['defaultreorderquantity'] = options.message;
        });

5 ) CONTROLLER SIDE VALIDATION IF REQUIRED

if (!ModelState.IsValid)
            {
if (ModelState["DefaultReorderQuantity"].Errors.Count > 0)
                {
                    return Json(new { Message = ModelState["DefaultReorderQuantity"].Errors[0].ErrorMessage, Status = "Fa" }, JsonRequestBehavior.AllowGet);
                }
                else
                {
                    return Json(new { Message = ResMessage.InvalidModel, Status = "Fa" }, JsonRequestBehavior.AllowGet);
                }
            }

AND YOU ARE DONE.... USE THIS AS PER YOUR REQUIREMENT ... HERE FIELD DEFAULT REORDER QUANTITY IS AN EXAMPLE ...

Monday, March 4, 2013

show hide div content using jquey

The HTML

Below is the sample text. Each text is wrapped in a DIV tag. Note that we have added a class “more” in each div. This class will decide if a text needs to be shortened and show more link showed or not.
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum laoreet, nunc eget laoreet sagittis, quam ligula sodales orci, congue imperdiet eros tortor ac lectus. Duis eget nisl orci. Aliquam mattis purus non mauris blandit id luctus felis convallis. Integer varius egestas vestibulum. Nullam a dolor arcu, ac tempor elit. Donec.
Duis nisl nibh, egestas at fermentum at, viverra et purus. Maecenas lobortis odio id sapien facilisis elementum. Curabitur et magna justo, et gravida augue. Sed tristique pellentesque arcu quis tempor.
consectetur adipiscing elit. Proin blandit nunc sed sem dictum id feugiat quam blandit. Donec nec sem sed arcu interdum commodo ac ac diam. Donec consequat semper rutrum. Vestibulum et mauris elit. Vestibulum mauris lacus, ultricies.

The CSS

Below is the CSS code for our example. Note the class “.morecontent span” is hidden. The extra text from the content is wrapped in this span and is hidden at time of page loading.
a {
 color: #0254EB
}
a:visited {
 color: #0254EB
}
a.morelink {
 text-decoration:none;
 outline: none;
}
.morecontent span {
 display: none;
}
.comment {
 width: 400px;
 background-color: #f0f0f0;
 margin: 10px;
}

The Javascript

Below is the Javascript code which iterate through each DIV tags with class “more” and split the text in two. First half is showed to user and second is made hidden with a link “more..”.
You can change the behaviour by changing following js variables.
  • showChar: Total characters to show to user. If the content is more then showChar, it will be split into two halves and first one will be showed to user.
  • ellipsestext: The text displayed before “more” link. Default is “…”
  • moretext: The text shown in more link. Default is “more”. You can change to “>>”
  • lesstext: The text shown in less link. Default is “less”. You can change to “<<"
$(document).ready(function() {
 var showChar = 100;
 var ellipsestext = "...";
 var moretext = "more";
 var lesstext = "less";
 $('.more').each(function() {
  var content = $(this).html();

  if(content.length > showChar) {

   var c = content.substr(0, showChar);
   var h = content.substr(showChar-1, content.length - showChar);

   var html = c + '' + ellipsestext+ ' ' + h + '  ' + moretext + '';

   $(this).html(html);
  }

 });

 $(".morelink").click(function(){
  if($(this).hasClass("less")) {
   $(this).removeClass("less");
   $(this).html(moretext);
  } else {
   $(this).addClass("less");
   $(this).html(lesstext);
  }
  $(this).parent().prev().toggle();
  $(this).prev().toggle();
  return false;
 });
});