Friday 24 May 2013

Jquery Method to Check the File upload control Empty or not, File Size and File Type(e.g. JPG,BMP,PDF)


Html:
<input type="file" id="file" name="file" />
<span id="valFile" class=""></span> // span for showing error message.

CSS:


.field-validation-error {
    color: #f00;
}

.field-validation-valid {
    display: none;
}

.input-validation-error {
    border: 1px solid #f00;
    background-color: #fee;
}


JQuery Snippet:
$(document).ready(function( )
{

//Changing the Error message of the File Upload and checking the File size and File type.
        $("#file").change(function () {

            $("#valFile").html("Please select file."); // Default Error Message
         
            var fileExtension = ['jpeg', 'jpg', 'png', 'gif', 'bmp', 'doc', 'docx', 'pdf'];

            if ($(this).val() != "") { //checking wheather the file uploader is empty or not
             
                //Checking the File type
                if ($.inArray($(this).val().split('.').pop().toLowerCase(), fileExtension) == -1) {
                    $(this).addClass("input-validation-error").removeClass("valid");
                    $("#valFile").addClass("field-validation-error").removeClass("field-validation-valid")
                        .html("Invalid Filetype(only image files/doc/docx/pdf)");
                }
                else {
                    $(this).removeClass("input-validation-error").addClass("valid");
                    $("#valFile").removeClass("field-validation-error").addClass("field-validation-valid");

                    if ((this.files[0].size > 4194304) && ($(this).val() != '')) {
                        $(this).addClass("input-validation-error").removeClass("valid");
                        $("#valFile").addClass("field-validation-error").removeClass("field-validation-valid")
                            .html("File size exceeded 4MB");
                    }
                }
            } else {
                $(this).addClass("input-validation-error").removeClass("valid");
                $("#valFile").addClass("field-validation-error").removeClass("field-validation-valid");
            }
        });

});

Happy Coding!

Wednesday 22 May 2013

How to create a File Upload with File Validation in Asp.net MVC / How to Use the @Html.TextBoxFor() for File Upload ?

While Wonder how to validate the Upload control in a easy way, I find this solution as the best to do it, although lot of other ways are found.This is because you need not need to write much more code as a normal razor validation will solve the problem.


My View:


 <div id="dvUpload" class="hide fieldControlContainer">
                <div class="innerDivLeft">
                    <label class="blue">Upload Document:</label>
                </div>
                <div class="innerDivRight">
                      @Html.TextBoxFor(model => model.File, new { @class = "inputTextBox", type="file" })
                      @Html.ValidationMessageFor(model => model.File)
                </div>
 </div>

The magic lies with this line  @Html.TextBoxFor(model => model.File, new { @class = "inputTextBox", type="file" }), here it will be rendered as a file upload control rather than a text because we are over riding the default behavior of input tag rendering by specifying it as type="file".

My Controller:



 public ActionResult Index(HttpPostedFileBase file, MyModel model)
        {
                  //Codes written here.
        }


MyModel:

public class MyModel
{

       [Required(ErrorMessage = "Please select file")]     // this is for model validation
        public HttpPostedFileBase File { get; set; }

}

Now your file upload validation will be checked like any other normal control.

Friday 17 May 2013

How to make a textbox to accept only integers as Input.

Html Page:
 <input type="text" name="age" id="txtAge" />&nbsp;<span id="errormsg"></span>

JQuery Snippet for the above TextBox:

Method-1:
$(document).ready(function () {
  //called when key is pressed in textbox
  $("#txtAge").keypress(function (e) {
     //if the letter is not digit then display error and don't type anything
     if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
        //display error message
        $("#errormsg").html("Digits Only").show().fadeOut("slow");
               return false;
    }
   });
});

Method-2:
$(document).ready(function () {
    $("#txtAge").keydown(function (e) {
        if (e.shiftKey) e.preventDefault();
        else {
            var nKeyCode = e.keyCode;
            //Ignore Backspace (Keycode=8), Tab keys(Keycode=9)  & Delete(Keycode=46)
         if (nKeyCode == 8 || nKeyCode == 9 || nKeyCode == 46) return;
            if (nKeyCode < 95) {
                if (nKeyCode < 48 || nKeyCode > 57) e.preventDefault();
            } else {
                if (nKeyCode < 96 || nKeyCode > 105) e.preventDefault();
            }
        }
    });
});

Enjoy!

Thursday 16 May 2013

Uploading a file to Server in Asp.net MVC 3 /4.



View page:


@using (Html.BeginForm("Index", "MyController", FormMethod.Post , new { enctype = "multipart/form-data" }))
{
//  Controls for your Model........(see below)

 <div>
                <div class="innerLeftContainer">
                    <label >Full Name:</label>
                </div>
                <div class="innerRightContainer">
                    @Html.TextBoxFor(model => model.FullName, new {@class = "inputTextBox"})
                    @Html.ValidationMessageFor(model=>model.FullName)
                </div>
            </div>


<div id="dvUpload">
                <div class="innerLeftContainer">
                    <label>Upload Document:</label>
                </div>
                    <div class="innerRightContainer">
                        <input type="file" id="DocumentUpload" name="file" />
                    </div>
            </div>


}


Note: The Form Method and the enctype is highly required for uploading your file to the server orthrwise you will always get the HttpPostedFileBase as null.


Action Method: ( in the Controller)
 [HttpPost]
        public ActionResult Index(HttpPostedFileBase file, MyModel model)
        {
            // Verify that the user selected a file
            if (file != null && file.ContentLength > 0)
            {
                // extract only the fielname
                var fileName = Path.GetFileName(file.FileName);
                if (fileName != null)
                {
                    // store the file inside ~/App_Data/uploads folder
                    var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
                    file.SaveAs(path);
                }
            }
            // redirect back to the index action to show the form once again
            return RedirectToAction("Index");
        }