HTML Radio Button & JQuery

 <input type="radio" name="ABC" value="a b c" />
 <input type="radio" name="ABC" value="x y z" />
var radioValue=  $('input[type=radio][name=ABC]:checked').val();
               
if (typeof radioValue=='undefined') {
    alert('Please select ...');
    return;
}

Submit HTML Form from JQuery

<input id="BrId" name="BrId" type="text" value="1">

<!-- HTML Form- -->
<form id="photoform" enctype="multipart/form-data" method="post" action="server-side-path">
    <input type="file" id="Photos" name="photo"/>
    <input type="hidden" name="VisitGuid" value="5" />
    <input type="hidden" name="HiddenBrId" id="HiddenBrId" value="" />
    <input type="submit" name="submit_btn" />
</form>
<script>
$('#photoform').on('submit', function (e) { 
     e.preventDefault();
     $('#HiddenBrId').val($('#BrId').val());
     $('#photoform')[0].submit();
});
</script>

Periodically send ajax request to server from JavaScript

<script>
    function executeQuery() {
        $.ajax({
            url: 'http://localhost:54802/Calls/CheckNewVoices/',
            type: 'POST',
            data: "{'lastcheckdatetime':'" + lastCheckDateTime + "'}",
            dataType: 'json',
            contentType:'application/json; charset=utf-8',
            success: function (response) {
                lastCheckDateTime = response.lastcheckdatetime;
                console.log(lastCheckDateTime);
                var files = response.files;
                files.forEach(function (file, index) {
                    //Do something
                });
                setTimeout(executeQuery, 30000); //Call after 30 seconds.
            }
        });
    }

    $(function () {
        setTimeout(executeQuery, 30000); //Call after 30 seconds.
    });
</script>

JQuery Selectors

$(document).on(‘click’, ‘.handle’, function (e) {

});

$(document).on(‘click’, ‘.Class:not(.Exception)’, function (e) {
});

//Zero-based
var rowIndex = $(‘#Table tr’).index(element.closest(‘tr’));
var currentTrPosition = rowIndex + 1;
var currentTR = $(“#Table tr:nth-child(” + currentTrPosition + “)”);

var inputs = currentTR.find(“input”);
var selects = currentTR.find(“select”);
inputs.attr(‘disabled’, ‘disabled’);
selects.attr(‘disabled’, ‘disabled’);

var trToShow = $(‘tr#’ + nextTrId);
trToShow.removeClass(‘Invisible’);

$(‘.Class’).not(‘.Exception’).change(function () {
});

$(‘.Class.Exception’).change(function () {
});

$InputElement.closest(‘h6’).next(‘h5’).removeClass(‘Invisible’);

JavaScript Model-AJAX- MVC Model

var data = {};
data.columnname = $InputElement.attr('data-columnname');
data.datatype = $InputElement.attr('data-datatype');
data.value = $InputElement.val();


$.ajax({
    type: 'POST',
    url: 'http://localhost:50929/Conversation/SubmitAnswer/', //last '/' is important

    contentType: 'application/json; charset=utf-8',
    data: JSON.stringify({ data: data }),
    dataType: 'json',
    beforeSend: function () {

    },
    success: function (response) {

    },
    error: function (request, status, error) {
    },
    complete: function () {
    }
});

public class Answer
{
    public string columnname { get; set; }
    public string datatype { get; set; }
    public string value { get; set; }
}


[HttpPost]
public JsonResult SubmitAnswer(Answer data)
{

}

Standard JQuery-Ajax Code Template (v.2)

$.ajax({
    type: 'POST',
    url: '../../../../AreaName(If any)/ControllerName/MethodName/',
    //If datatype is of FormCollection, following 3 lines are not needed-
    //====================================================
    //contentType: 'application/json; charset=utf-8',
    //data: "{'agentdata':'"+ agentdata +"'}",
    //OR, data:JSON.stringify({ key1: value1, key2: value2}),
    //dataType: 'json',
    //====================================================
    //If datatype is of FormCollection, following 3 lines are needed-
    //====================================================
    //processData: false,  // tell jQuery not to process the data
    //contentType: false,   // tell jQuery not to set contentType    
    //data: Data,
    //====================================================
    beforeSend: function () {
        $('SubmitButton').attr('disabled', 'disabled');
        $('SubmitButton').html('Working…');
    },
    success: function (result) {
        if (result == 'Success') {
            SuccessfullSaveNotification();
            ResetMainForm(MainForm);
        }
        else {
            ShowRegularError(result);
        }
    },
    error: function (request, status, error) {
        ShowRegularError('Failed to save. Error Details – Request: ' + request + ', Status: ' + status + ', Error: ' + error);
    },
    complete: function () {
        $('SubmitButton').removeAttr('disabled');
        $('SubmitButton').html('Save changes');
    }
});

Create JavaScript Array in ASP.NET MVC Razor

Let’s you need to populate this variable in javascript-

Divisions= ["Dhaka", "Khulna", "Rajshahi"];

Way 1: Done in javascript tag.

<script>
  //first declare an empty array
  var Divisions = []; 
  
  //Razor Loop
  @foreach (var row in ViewBag.DivisionTable.Rows)
  {
     <text>
       Divisions.push('@row["DisionName"].ToString()');
     </text>
  }
</script>

Way 2: Done in C#

string[] Divisions = new string[qty];
//int[] data = new int[qty];

for (int i = 0; i < DivisionQty; i++)
{
   Divisions[i]= Table.Rows[i]["DivName"].ToString();
}

ViewBag.Divisions=Divisions;

//Now in javascript-
var Divisions = @Html.Raw(Json.Encode(ViewBag.Divisions));

Menu navigation technique in SPA

Untitled-1

Navigation/Menu demands some extra atttention in a single page application. Since, master/shell page does not refresh, so it requires to mark an menu item active and other inactive (i.e. add/remove styles).

And, finally laod the partial content.

/*CSS to spin the preloader image*/
.imagee {
    overflow: hidden;
    transition-duration: 0.8s;
    transition-property: transform;
}

.imagee:hover {
    transform: rotate(360deg);
}

.imageee {  
     margin: -60px 0 0 -60px;
    -webkit-animation: spin 2s linear infinite;
    -moz-animation: spin 2s linear infinite;
    animation: spin 2s linear infinite;
}

@-moz-keyframes spin {
    100% {
        -moz-transform: rotate(360deg);
    }
}

@@-webkit-keyframes spin {
    100% {
        -webkit-transform: rotate(360deg);
    }
}

@@keyframes spin {
    100% {
        -webkit-transform: rotate(360deg);
        transform: rotate(360deg);
    }
}
<ul class="navigation">
    <li class="active">
        <a class="handle-link" href="index.html" title=""><img src="dashboard.png" />Dashboard</a>
    </li>

    <li class="has-sub-menu">
        <a href="#" title=""><img src="form-elements.png" />Multiple<strong>3</strong></a>
        <ul>
            <li>
                <a class="handle-link sub-menu" href="forms.html" >One</a>
            </li>
            <li>
                <a class="handle-link sub-menu" href="two.html">Two</a>
            </li>
            <li><a class="handle-link sub-menu" href="three.html" >Three</a></li>
        </ul>
    </li>
    <li >
        <a class="handle-link" href="index.html"><img src="dashboard.png" />Single
        </a> 
    </li>

    <li class="has-sub-menu">
        <a href="#"><img src="elements.png"/>This is Multiple also<strong>2</strong></a>
        <ul>
            <li>
                <a class="handle-link sub-menu" href="forms.html" >One</a>
            </li>
            <li>
                <a class="handle-link sub-menu" href="form_wizards.html" title="">Two</a>
            </li>
        </ul>
    </li>
</ul>
$('a.handle-link').click(function (e) {
    e.preventDefault();
    var currentMenuItem = $(this);
    var currentLinkAddress = $(currentMenuItem).attr('href');
    var currentLI = currentMenuItem.closest('li');

    var img; //variable to hold currently displaying preloader.

    //Check this is sub-menu --->
    if (currentMenuItem.hasClass('sub-menu'))
    {  //If this is a sub-menu item ---->

        var currentUL = currentLI.closest('ul');
        var parentLI = currentUL.closest('li');

        //Checking whether it has 'current' class ---->
        if (currentLI.hasClass('current')) 
        { //if it has 'current' class -->
            //This is current and its top li is also active. So no need to do any class removing code.
            //But user may want to reload this page. So, show the preloader
            //Showing preloader--->
            var firstAnchor = parentLI.find('a:first');
            img = firstAnchor.find('img');
            img.addClass('imageee');
            //Showing preloader---<
        } //if it has 'current' class ---<
        else 
        { //if it does not have 'current' class --->

            //But it might be the sub-menu under the same menu. So check it now.
            if (parentLI.hasClass('active'))
            { //If it's under same parent menu--->
                //No need to check whether another element has 'imageee' class
                //Just show the preloader
                var firstAnchor = parentLI.find('a:first');
                img = firstAnchor.find('img');
                img.addClass('imageee');

                // So, no need to change active. But change only 'current' class
                currentUL.find('li').each(function (i) {
                    if ($(this).hasClass('current')) {
                        $(this).removeClass('current');
                    }
                });
                currentLI.addClass('current');
            } //If it's under same parent menu ---<
            else
            { //If parent li does not have 'active' class --->
                //But other menu/sub-menu may have 'active' class or display preloader. So check it.
                var baseUl = parentLI.closest('ul');
                baseUl.find('li').each(function (i) {
                    if ($(this).hasClass('active')) {
                        $(this).removeClass('active');

                        //Hide all other (if any) preloader--->
                        var otherAnimatingImage = $(this).find('img');
                        if (otherAnimatingImage.hasClass('imageee')) {
                            otherAnimatingImage.removeClass('imageee')
                        }
                        //Hide all other (if any) preloader---<

                        if ($(this).hasClass('has-sub-menu')) {
                            $(this).find('li').each(function (i) {
                                if ($(this).hasClass('current')) {
                                    $(this).removeClass('current');
                                }
                            });
                        }
                    }
                });

                parentLI.addClass('active');
                currentLI.addClass('current');
                //Show preloader--->
                var firstAnchor = parentLI.find('a:first');
                img = firstAnchor.find('img');
                img.addClass('imageee');
                //Show preloader ----<
            } //If parent li does not have 'active' class ---<
        } //If it does not have 'current' class ---<
        //Checking whether it has 'current' class ----<
    } //If this is a sub-menu item ----<
    else
    { //If this is not sub-menu ---->
        var baseUl = currentLI.closest('ul');
        baseUl.find('li').each(function (i) {
            if ($(this).hasClass('active')) {

                //Hide all other (if any) preloader--->
                var otherAnimatingImage = $(this).find('img');
                if (otherAnimatingImage.hasClass('imageee')) {
                    otherAnimatingImage.removeClass('imageee')
                }
                //Hide all other (if any) preloader--->

                $(this).removeClass('active');
                if ($(this).hasClass('has-sub-menu')) {
                    $(this).find('li').each(function (i) {
                        if ($(this).hasClass('current')) {
                            $(this).removeClass('current');
                        }
                    });
                }
            }
        });

        currentLI.addClass('active');

        img = currentMenuItem.find("img");
        img.addClass('imageee');
    } //If this is not sub-menu ---->
    //Check this is sub-menu --->

    //Finally, ajax call to load partial ---->
    $.ajax({
        url: currentLinkAddress,
        async: true,
        beforeSend: function () {
            // $("#PartialContent").fadeOut("slow").empty();
            //$('#PartialContent').fadeTo('slow', 0);
        },
        success: function (data) {
            //  $('#PartialContent').fadeTo('slow', 0).slideUp()
            $('#PartialContent').html(data).fadeIn("slow");
        },
        error: function (request, status, error) {
            //  alert("Error-  Request: " + request + ", Status: " + status + ", Error: " + error);
            var msg = '<div class="notice outer"> \
                            <div class="note note-danger">  \
                            <button type="button" class="close">×</button>   \
                                <strong>Notice!</strong> Something is wrong. Please reload the page.  \
                            </div>  \
                        </div>';
            $('#PartialContent').html(msg).fadeIn("slow");

        },
        complete: function () {
            img.removeClass('imageee');
        }
    });
    //Finally, ajax call to load partial ----<
});


Upload multiple files using AJAX- ASP.NET MVC (multiple file input with same class)

This technique is used to upload multiple files/photos by using multiple file input control (dynamically added), AJAX and ASP.NET-

1. Multiple file input control (with same .class)
2. JQuery AJAX
3. Form collection for additional data
4. ASP.NET MVC

HTML Part
----------------------------------------

<div class="form-group">
    <input class="multiplephoto" type="file" name="files" multiple />
</div>

<button id="AddMorePhoto">Add more photo </button>
Adding another file input
-----------------------------------------

 $('#AddMorePhoto').on('click', function (e) {
         e.preventDefault();
         $('<div/>').addClass('form-group')
         .html($('<input class="button multiplephoto" type="file" name="files" multiple />'))
         .insertBefore(this);

 });


Submitting the form as FormData via AJAX
-----------------------------------------

var fd = new FormData();

//append some other data to fd. i.e.-
fd.append('PersonName', personName);

var inputs = $('.multiplephoto');
$.each(inputs, function (obj, v) {
    var file = v.files[0];
    fd.append("photos", file);
    //var filename = $(v).attr("data-filename");
});

$.ajax({
    url: "/ControllerName/ActionMethodName",
    type: "POST",
    data: fd,
    processData: false,  // tell jQuery not to process the data
    contentType: false,   // tell jQuery not to set contentType
    beforeSend: function () {
    },
    success: function (response) {
    },
    error: function (request, status, error) {
    },
    complete: function () {
    }

});
Server-side code
------------------------------------

[HttpPost]
public JsonResult GetPhotos(IEnumerable<HttpPostedFileBase> photos, FormCollection data)
{
    var directory = HttpContext.Server.MapPath("~/Photos");
                
    foreach (var file in photos)
    {
        String fileName = file.FileName;
        string imagePath = Path.Combine(directory, "LoginPhotos", fileName);
        file.SaveAs(imagePath);
    }

    return Json("success");

}