Showing posts with label jquery. Show all posts
Showing posts with label jquery. Show all posts

Disable textbox cut copy paste in asp.net and asp.net mvc using javascript,jquery

Udemy
In some scenarios, we don't want user to be able to cut or copy the value of text box and we also want to restrict user to not be able to paste value from clipboard in text box.


User have couple of options, he can use short cut keys , for example Ctrl + C for copying and Ctrl + V , or user can right click inside the control and can use use context menu buttons which are mostly Cut, Copy and Paste available for doing desired operation on control.


One way is to write java-script events  for cut,copy and paste so that whenever user do one of these operations on control we handle them to override the default implementation of these commands.



In asp.net mvc we can use the htmlAttributes parameter of Html Helper method do it.

Disabling Using  JavaScript:


Here is an example code using javacript:

@Html.TextBoxFor(model => model.Question, 
          new {
                       @class="form-control",
                       oncut="return false"
                       oncopy="return false", 
                       onpaste="return false"
                     }
                 )

Here is the Live DEMO Fiddle of it.


Disabling Using JQuery:


We can do the same using jquery as well this way:

@Html.TextBoxFor(model => model.Question, 
          new {
                       @class="form-control",
                       id="txtQuestion"
                       oncut="return false"
                       oncopy="return false", 
                       onpaste="return false"
                     }
                 )

and in jquery :

$("#txtQuestion").on("cut copy paste",function(e) {

   e.preventDefault();
    // it will cause to stop default behaviour ofcommand
   // or we can use return false as well, as we did in js

}

 You can do it same way in asp.net web forms as well, for example:

<asp:TextBox ID="txtQuestion" 
             runat="server"
             CssClass="form-control"
             oncut="return false"
             oncopy="return false" 
             onpaste="return false">
</asp:TextBox>



difference between ~= and *= in jquery

Udemy
Few days back, i saw a SO question, that what is the difference between [attribute~=value] and [attribute*=value]?



*= is attributeContains selector , From jquery docs:
Selects elements that have the specified attribute with a value containing a given substring.
~= is attributeContainsWord selector , From jquery docs:
Selects elements that have the specified attribute with a value containing a given word, delimited by spaces.


The attributeContains selector is for the string to be contained in the attribute value while attributeContainsWord selector is for string seperated with delimeted space. The official jquery examples clearly explain it.



Attribute Contains Selector [name*="value"]

HTML:

<input name="man-news">
<input name="milkman">
<input name="letterman2">
<input name="newmilk">
JQUERY:

$( "input[name*='man']" ).val( "has man in it!" );
OUTPUT:


Here is the fiddle demonstrating the Attribute Contains Selector [name*="value"] behavior

Attribute Contains Word Selector [name~="value"]

HTML:

<input name="man-news">
<input name="milk man">
<input name="letterman2">
<input name="newmilk">
JQUERY:


$( "input[name~='man']" ).val( "mr. man is in it!" );

OUTPUT:

Here is example demonstrating the behavior of  Attribute Contains Word Selector [name~="value"] 




Searchable Dropdown in Asp.net mvc 4

Udemy

Today i am writing about how to implement searchable dropdown list in asp.net mvc 4. Actually i came across a scenario where the drop down elements were too large and its troublesome for user to find the option that user wants to select to i needed to add searching so that it becomes easy for user.


To Implement this i used a jquery library namely Jquery chosen you can find it by searching on google or can download from here,Its pretty simple actually you just need to include the jquery chosen js file and css file in your porject and after that one simple step to do and you are done.

You have to add css classattribute value  "chosen-select" in the dropdown select attribute.

For Example, Here is my dropdown html:

<select class="chosen-select" id="SubDepartmentsDDL" name="SubDepartmentsDDL">

  <option value="1">Hematology (2)</option>
  <option value="2">Clinical Chemistry (0)</option>
  <option value="3">Histopatholgy (0)</option>
  <option value="8">Molecular Lab (0)</option>
  <option value="9">General Radiology (0)</option>
  <option value="10">Ultrasound (0)</option>
  <option value="12">ECG (0)</option>
  <option selected="selected" value="13">Microbiology (0)</option>
  <option value="14">Blood Bank (0)</option>
  <option value="16">Special Chemistry (1)</option>
  <option value="18">Services (0)</option>
  <option value="19">International Send Outs - India (0)</option>
  <option value="20">National Send Outs (0)</option>
  <option value="21">Vaccination (0)</option>
  <option value="22">ABC (0)</option>

</select>




you will have to include the follwing js and css files you will find the downloaded jquery chosen folder:

<link href="/PulseBeta/css/chosen.css" rel="stylesheet" type="text/css">
<link href="/PulseBeta/css/prism.css" rel="stylesheet" type="text/css">
<script type="text/javascript" src="/PulseBeta/js/chosen.jquery.js"></script>
<script type="text/javascript" src="/PulseBeta/js/prism.js"></script>

Now in the page write this script and you are done:

<script type="text/javascript">

         var config = {
             '.chosen-select': {},
             '.chosen-select-deselect': { allow_single_deselect: true },
             '.chosen-select-no-single': { disable_search_threshold: 10 },
             '.chosen-select-no-results': { no_results_text: 'Oops, nothing found!' },
             '.chosen-select-width': { width: "95%"}//,
             //'.chosen-search': {disable_search: false}
         }
         for (var selector in config) {
             $(selector).chosen(config[selector]);
         }

</script>


Before this my dropdown like this:







and after applying chosen plugin the result is:





Cheers...





Infinite Scroll Paging in Asp.net mvc 4

Udemy
Today i am sharing another feature which Facebook and LinkedIn like paging, i came across a scenario to show doctors list in our database, instead of paging i thought to go for infinite scroll paging like Facebook LinkedIn, on page load i show top 10 or 20 doctors and as user scrolls down i load more doctors via Ajax.


Here i go with the HTML of my view:

<div class="grid-content overflow" id="docsContainer">
<!--grid area -->
    <!--grid area end -->

    <br />
<div style="clear: both;">
</div>
<div class="clearfix">
</div>
@if (ViewBag.Refreshed == "YES")
    {
        <input id="lastDoctorID" type="hidden" value="0" />
    }
    else
    {
        <input id="lastDoctorID" type="hidden" />
    }
    <input id="GetFlag" type="hidden" value="true" />
</div>


On page load i am getting to 20 records from database, here it is:

$(document).ready(function () {


        if ('@ViewBag.Refreshed' == "YES") {

            $('input#lastDoctorID').val("0");

        }

        GetDoctors();

});


here is definition of GetDoctors Method which sends Ajax call to a WCF service which returns result as JSON back:

function GetDoctors() {

        if ($('input#lastDoctorID').val() != null) {

            lastID = $('input#lastDoctorID').val();

        }
        else {

            lastID = 0;
        }

        var url = '@Url.Action("GetDoctors", "SearchPathologist")';

        url = url + "?lastDoctorID=" + lastID;
        $('div#divLoading').show();
        $.ajax({
            type: 'POST',
            url: url,

            success: function (response) {
                // your code from above
                $('div#docsContainer').append(response);
                $('div#divLoading').hide();
                if (response == "ok") {


                }

                else {


                }
            },
            error: function (xhr, textStatus, error) {
                //$('span#loader_' + ID).hide();
                console.log(xhr.statusText);
                console.log(textStatus);
                console.log(error);
                $.fallr('show', {
                    content: 'Request Sending Failed! Try Again after few minutes.

'
                });
            }
        });
    }

In my action i am calling a web-service which return Data-Set and i extract data and create list and pass it to partial view which in rendered on the page.

Here is the action code:

public ActionResult GetDoctors(string lastDoctorID)
        {
            using (OliveCliqService.OliveServiceClient client = new OliveCliqService.OliveServiceClient())
            {

                DataSet result = client.GetDoctorsList(Session["userID"].ToString(),lastDoctorID);

                List doctorsList = new List();

                for (int i = 0; i < result.Tables[0].Rows.Count; i++)
                {

                    CliqDoctor doctor = new CliqDoctor();

                    doctor.DoctorID = int.Parse(result.Tables[0].Rows[i]["DoctorID"].ToString());
                    doctor.Name = result.Tables[0].Rows[i]["FirstName"].ToString() + " " + result.Tables[0].Rows[i]["LastName"].ToString();

                    doctor.Designation = result.Tables[0].Rows[i]["Designation"].ToString();
                    doctor.Speciality = result.Tables[0].Rows[i]["Spaciality_name"].ToString();
                    doctor.Location = result.Tables[0].Rows[i]["Address"].ToString();
                    doctor.ImageName = result.Tables[0].Rows[i]["Image"].ToString();
                    doctor.Friend = result.Tables[0].Rows[i]["Friend"].ToString();

                    doctorsList.Add(doctor);

                }


                return PartialView("~/Views/Shared/_DoctorPartial.cshtml", doctorsList);
            }
        }

Here is my web service method definition:

public DataSet GetDoctorsList(string PersonId,string lastDoctorID)
        {

            string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["OliveCliq"].ConnectionString;


            MySqlConnection con = new MySqlConnection(connectionString);
            con.Open();
            string cmd = @"SELECT d.DoctorID,d.FirstName,d.LastName,d.Image,de.Designation,d.Address,s.Spaciality_name,
CASE WHEN EXISTS (SELECT id FROM cloud_clinic.doctor_members dm WHERE dm.doctor_id = '" + PersonId + "' AND dm.member_id = d.doctorID) THEN 'YES' ELSE 'NO' END AS Friend FROM cloud_clinic.doctors d LEFT OUTER JOIN cloud_clinic.clinic_doctor_designations cdd on d.doctorid = cdd.doctor_id LEFT OUTER JOIN cloud_clinic.rm_pr_designations de on cdd.designation_id = de.designationid LEFT OUTER JOIN cloud_clinic.doctor_spcialities ds on d.doctorID = ds.doctorid LEFT OUTER JOIN cloud_clinic.spaciality s on ds.spacialityID = s.id where d.DoctorID > '"+lastDoctorID+"' Group by d.DoctorID Order by d.DoctorID LIMIT 30";

            MySqlDataAdapter da = new MySqlDataAdapter(cmd, con);

            DataSet ds = new DataSet();

            da.Fill(ds);

            return ds;
            
        }

When user scroll down, new records are fetched Ajax call and appended on the page, here is that JQuery snippet:

 $(document).ready(function () {
        $(window).scroll(function () {
            console.log("document height:" + $(document).height());
            console.log("window height:" + $(window).height());
            console.log("window scroll:" + $(window).scrollTop());
            if ($(window).scrollTop() + $(window).height() == $(document).height()) {
                GetDoctors();
            }
        });
    });

Hope you understood it.

Cheers!

Thanks



How to detect user reached bottom of page while scrolling

Udemy
Few days before i needed to implement on scroll paging as the facebook or linkedin is doing, instead of paging i thought to do infinite page scroll paging in my application so i decided to share the thing here as well.


Here is a sample code. Add this html to a empty html page:


<div style="height: 4000px">Scroll down!</div>

Here is the jquery code, but remeber to add jquery minified version in your page head as well like this:


<script type="text/javascript"
    src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>


Here is the jquery code to detect if user has reached page end while scrolling:


<script type="text/javascript">

        $(window).scroll(function () {
            if ($(window).scrollTop() + $(window).height() == $(document).height()) {
                alert("bottom!");
            }
        });

    
    </script>


here is the code to detect if user is near the bottom:


 $(window).scroll(function() {   
   if($(window).scrollTop() + $(window).height() > $(document).height() - 100) {
       alert("bottom!");
   }
});

Hope you got it. -:)




Asp.net mvc Ajax File Uploading using JQuery

Udemy

Introduction:

In this post, you will learn how to upload file in asp.net mvc without reloading the whole page or wihtout refreshing the whole page instead we will update specific portion of page which is normally said aync postback in webforms terms.

Background:

Once upon a time i came across scenario where i needed to upload file in my asp.net mvc web application but its quite simple if we want full post-back, but i was thinking of doing it using Ajax by doing Partial Post-back.

Using JQuery to post standard forms is extremely simple, but when posting multi-part forms for uploading files it's not so intuitive.  This is due to browser security restrictions and sandboxing.  Today I'm going to show you how to fake an asynchronous upload without reloading the page and get a result back from the server.

 First Idea that came in my mind was using mvc helper Ajax.BeginForm and i came to know that it not supports file upload by partial post-back, it will do post-back.


Second Idea that was in my mind is to use JQuery and AJAX to post file on server so that i can avoid post-back, i tried my own way by posting file and returning partial view via AJAX but same issue was happening the partial view was rendering independently not on the same view, then i  searched on internet and found a way.

This method uses IFrame and do a fake async postback and it looks like that file uplaoding via ajax, as our view remains same.

How It Works

In order to make the AJAX style file uploads work, we need to to post to an iFrame.  We're going to position an iFrame off the page to hide it and then post to it.  We'll return a partial view to the page and append it in some html container.  It's important to note that due to security limitations, the page being posted to must be on the same domain as the page you're posting from. Also, this solution will be using a single hidden iFrame, but for multiple simultaneous uploads you could dynamically generate the iFrames and post to them.

Main View

Here is my view code i have created a form using mvc Helper and after the form i added an iframe in which our form will be posted:

@{
    ViewBag.Title = "Ajax File Uploading";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Ajax File Uploading</h2>


<div>

    <div>
        <h1>Upload File</h1>
    </div>


    @using (Html.BeginForm("Upload", "Home", FormMethod.Post,
    new
    {
        enctype = "multipart/form-data",
        id = "ImgForm",
        name = "ImgForm",
        target = "UploadTarget"
    }))
    {
        
@* DataBase Record ID as Hidden Field against which we are uplaoding file  *@
         
        @Html.Hidden("ID", 65512)
        <div style="width: 100px; margin: auto; float: left; line-height: 30px; font-weight: bold;">File</div>
     
         
        <div style="width: 200px; float: left; margin: auto;">

            <input type="file" id="uploadFile" name="file" data-val="true" data-val-required="please select a file" />
            <span id="validityMessages" style="color: Red;"></span>
        </div>

         
        <div style="clear: both;"></div>
     
        <div style="width: auto; margin-top: 3%;">
            <div style="margin: 5% 18%;">
                <input id="upload" type="button" value="Upload" name="Upload" onclick="UploadImage()" />
                <span id="uploadLoader" style="display: none;">
                    <img id="searchLoader" src="@Url.Content("~/Content/Images/loader.gif")" />Uploading Please Wait</span>
            </div>
        </div>
           
     
    }
    <div id="uploadsContainer"></div>
    <iframe id="UploadTarget" name="UploadTarget" onload="UploadImage_Complete();" style="position: absolute; left: -999em; top: -999em;"></iframe>
</div>




@section Scripts{

    <script type="text/javascript">

        $(document).ready(function () {

            $('img.delUpload').live('click', function () {

                var Id = this.id;

                var url = '@Url.Action("DeleteFile","Home")';

                url = url + "?id=" + Id
                $.get(url, function (response) {

                    $('#uploadsContainer').html(response);


                });


            });

        });


    </script>



    <script type="text/javascript">
        var isFirstLoad = true;

        function UploadImage() {



            // check for size of file not greater than 1MB
            if ($("#uploadFile").val()) {


                var iSize = ($("#uploadFile")[0].files[0].size / 1024);


                iSize = (Math.round((iSize / 1024) * 100) / 100);

                if (iSize > 4) {

                    alert("File must be less than 4MB");

                    $('span#validityMessages').html("File must be less than 4MB");



                    return;

                }
                else {
                    // on form post showing Busy Indicator
                    $('#uploadLoader').show();
                    $("#ImgForm").submit(); // post form
                    console.log(iSize + "Mb");
                }
            }

                // check for no file selected for upload

            else {


                $('span#validityMessages').html("Please select a File of size less than 4MB!");


                return;
            }


        }

        function UploadImage_Complete() {
            //Check to see if this is the first load of the iFrame
            if (isFirstLoad == true) {
                isFirstLoad = false;

            }


            $('#uploadLoader').hide();


            //Reset the image form so the file won't get uploaded again
            document.getElementById("ImgForm").reset();

            // this call will get uploads if any exists on server against this id and after successfull upload refreshing partial view to get the latest uploads
            GetFiles();


        }


        function GetFiles() {

            var url = '@Url.Action("GetFiles","Home")';

            var Id = $('input#ID').val();
            url = url + "?id=" + Id
            $.get(url, function (response) {

                $('#uploadsContainer').html(response);


            });

        }

    </script>
}

 Uploads ViewModel

Here is my uploads view model which is strongly typed with the uploads partial view:

public class UploadsViewModel
    {
        public long ID { get; set; }
        public List Uploads { get; set; }

        public UploadsViewModel()
        {
            this.Uploads = new List();
        }
    }


    public class File
    {
        public string FilePath { get; set; }
        public long FileID { get; set; }
        public string FileName { get; set; }
    }

Upload Controller Method

Here is my controller method, i am taking two parameters input one is the posted form, in form i am posting some values in hidden fields required for DB updates and second parameter is posted file, i am simply saving the file in Uploads directory on server and updating a table in DB using Entity Framework and at the end returning partial view which will display the uploaded file name, thumbnail if its a image type file and button for deleting the file.

For this post i am storing the state in Session:

        [HttpPost]
        public ActionResult Upload(FormCollection form, HttpPostedFileBase file)
        {
            
            UploadsViewModel uploadsViewModel = Session["Uploads"] != null ? Session["Uploads"] as UploadsViewModel : new UploadsViewModel();


            uploadsViewModel.ID = long.Parse(form["id"]);

            File upload = new File();
            upload.FileID = uploadsViewModel.Uploads.Count + 1;
            upload.FileName = file.FileName;
            upload.FilePath = "~/Uploads/" + file.FileName;

            

            //if (file.ContentLength < 4048576)    we can check file size before saving if we need to restrict file size or we can check it on client side as well
            //{

                if (file != null)
                {
                    file.SaveAs(Server.MapPath(upload.FilePath));
                    uploadsViewModel.Uploads.Add(upload);
                    Session["Uploads"] = uploadsViewModel;
                }

                // Save FileName and Path to Database according to your business requirements

            //}


            return PartialView("~/Views/Shared/_UploadsPartial.cshtml", uploadsViewModel.Uploads);
        }



Uploads Partial View

Here is my partial view code:

@model List<AjaxFileUploading.ViewModels.File>
@{
    Layout = null;
    var IsAnyImage = Model.Any(x => new String[] { "jpg", "jpeg", "png", "gif" }.Contains(x.FileName.Split('.').Last()));

}


@if (Model.Any())
{
    <h3>Uploads</h3>
    <hr />
    <table style="width: 500px;">
        <tr>
            @if (IsAnyImage)
            {
                <th>Thumbnail</th>
            }
            <th>FileName</th>
            <th>Action</th>
        </tr>
        <tbody>
            @for(int i=0; i< Model.Count; i++)
            {
                <tr>

                    
                        <td style="text-align: center;">
                            <img width="60" src="@Url.Content(Model[i].FilePath)" />

                        </td>
                    
                    

                    <td style="text-align: center;">
                        <a href="@Url.Content("~/Uploads/" + Model[i].FileName)" target="_blank">@Model[i].FileName</a></td>
                    <td style="text-align: center;">
                        <img id="@Model[i].FileID" class="delUpload" width="20" src="@Url.Content("~/Content/Images/delete.png")" /></td>
                </tr>
            }
        </tbody>
    </table>

}
else
{
    <h3>No Uploads Found!</h3>
}



Javascript and Jquery for MainView

The first thing we need to do is include a version of jQuery.  Since I'm writing an MVC application, I've chosen to use bundles that are provided by the framework, so you will see follwing line written in master layout _Layout.cshtml which is located in Views >> Shared  directory:

    @Scripts.Render("~/bundles/jquery")

Now we can start creating our JavaScript to handle our form posts.  The UploadImage() method isn't absolutely necessary since all our example does is post the form, however as in my case i am displaying a busy indicator so that user is acknowledged that  file is uploading.  Here we're just going to create a global variable that tells whether or not we're on the first load of the iFrame and the function to upload the image:


Now the form is setup to post to our iFrame. Here is the code which checks if any file exists against this record already it is displayed and validation is also applied in this event, actually this event will be called when iframe will load, on first pageload also iframe load event is called so thats why i have put validation code as well here, i am just checking by flag is it a first load of iframe or not, if it's not first load then it means user is uploading file and  we may want to validate on file size, i am not allowing file greater than 4MB, you can also check here for file extension as well, may be you just want to allow user to upload images so in this function you can check that as well if you  want to check on specific type of files to be just uploaded :

<script type="text/javascript">
        var isFirstLoad = true;

        function UploadImage() {



            // check for size of file not greater than 1MB
            if ($("#uploadFile").val()) {


                var iSize = ($("#uploadFile")[0].files[0].size / 1024);


                iSize = (Math.round((iSize / 1024) * 100) / 100);

                if (iSize > 4) {

                    alert("File must be less than 4MB");

                    $('span#validityMessages').html("File must be less than 4MB");



                    return;

                }
                else {
                    // on form post showing Busy Indicator
                    $('#uploadLoader').show();

                    console.log(iSize + "Mb");
                }
            }

                // check for no file selected for upload

            else {


                $('span#validityMessages').html("Please select a File of size less than 4MB!");


                return;
            }


        }

        function UploadImage_Complete() {
            //Check to see if this is the first load of the iFrame
            if (isFirstLoad == true) {
                isFirstLoad = false; 

            }


            $('#uploadLoader').hide();


            //Reset the image form so the file won't get uploaded again
            document.getElementById("ImgForm").reset();

            // this call will get uploads if any exists on server against this id and after successfull upload refreshing partial view to get the latest uploads
            GetFiles();


        }

</script>    

and at last here is the deleting of file using ajax:

        $(document).ready(function () {

            $('img.delUpload').live('click', function () {

                var Id = this.id;

                var url = '@Url.Action("DeleteFile","Home")';

                url = url + "?id=" + Id
                $.get(url, function (response) {

                    $('#uploadsContainer').html(response);


                });


            });

        });



Delete File Controller Method

 Here is the Delete File Action:

        public ActionResult DeleteFile(long id)
        {

            /* Use input Id to delete the record from db logically by setting IsDeleted bit in your table or delete it physically whatever is suitable for you
               for DEMO purpose i am stroing it in Session */

            UploadsViewModel viewModel = Session["Uploads"] as UploadsViewModel;

            File file = viewModel.Uploads.Single(x => x.FileID == id);

            try
            {

                System.IO.File.Delete(Server.MapPath(file.FilePath));
                viewModel.Uploads.Remove(file);

            }

            catch (Exception)
            {
                return PartialView("~/Views/Shared/_UploadsPartial.cshtml", viewModel.Uploads);
            }



            return PartialView("~/Views/Shared/_UploadsPartial.cshtml", viewModel.Uploads);
        }


and GetFiles actions looks like :
        public ActionResult GetFiles(long Id)
        {
            UploadsViewModel viewModel = Session["Uploads"] as UploadsViewModel;

            return PartialView("~/Views/Shared/_UploadsPartial.cshtml", (viewModel == null ? new UploadsViewModel().Uploads : viewModel.Uploads));
        }



I have created a sample project to demonstrate it.The screen shot is attached:


You can download sample source code from here

Download Source Code (AjaxFileUploading.zip) 


Hope you will get the understanding how its working, for reference from where i got help you can also visit this link for more details: AJAX File Uploads with jQuery and MVC 3