Upload multiple files ASP.NET MVC without AJAX

<form enctype="multipart/form-data" action="/SubmitImage"
         method="post" >
    <input type="file" name="photos" multiple />
    <input type="text" name="caption"/>
    <textarea name="description"></textarea>
    <input type="submit" value="Submit" />
</form>
[ValidateInput(false)]
[HttpPost]
public ActionResult SubmitImage(IEnumerable<HttpPostedFileBase> photos,
                                   FormCollection data)
{
    String authString = Request.QueryString["auth"].ToString();
 
    String caption = data["caption"].ToString();
    string description = data["description"].ToString();
 
    if (Request.Files["photos"] != null)
    {
        //The directory where photo will be saved.
        var directory = HttpContext.Server.MapPath("~/Photos");
        foreach (var photo in photos)
        {
            //Get the file name of photo as it being sent.
            //It's required to get the original file extension.
            var photoName = photo.FileName.ToString();
            var extension = Path.GetExtension(photoName).ToLower();
            //Give photo a new name so that it can avoid duplicate name.
            var newName = Guid.NewGuid() + extension;
            string filePath = Path.Combine(directory, newName);
 
            //Check file existence. If exist, try another name.
            if (System.IO.File.Exists(filePath))
            {
               newName = Guid.NewGuid() + extension;
            }
             
            string filePath = Path.Combine(directory, newName);
            photo.SaveAs(filePath); //saving the photo to directory.                    
        }
    }
 
    return RedirectToAction("Index", "UploadImage", new { auth = authString, issubmitted = true });
}
Advertisements

Upload multiple files using AJAX- ASP.NET MVC

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

1. Single file input control
2. JQuery AJAX
3. Form collection for additional data
4. ASP.NET MVC

<input type="file" id="Photos" multiple />
<!--Save button is disabled to prevent empty file submission-->
<button id="SavePhotos" disabled>Save</button>
<script>
$(function () {
    var fd, saveButton = $("#SavePhotos");
    $("#Photos").change(function (e) {
        fd = new FormData();
        fd.append("id", 1);    
        $.each(e.target.files, function (index, file) {
            fd.append("photos", file);
        });
        saveButton.prop("disabled", false)
    });

    saveButton.click(function () {
        $.ajax({
            url: URL-To-Submit,
            type: 'POST',
            data: fd,
            processData: false,
            contentType: false,
            beforeSend: function () {
            },
            success: function (response) {
                console.log(response);
            },
            error: function (request, status, error) {
            },
            complete: function () {
            }
        });
    });
});
[HttpPost]
public JsonResult SavePhotos(IEnumerable<HttpPostedFileBase> photos, FormCollection data)
{
    try
    {
        var directory = HttpContext.Server.MapPath("~/Photos");

        foreach (var file in photos)
        {
            String fileName = file.FileName;
            String fileExtension = Path.GetExtension(fileName);

            string imagePath = Path.Combine(directory, "HubPhotos", fileName);
            file.SaveAs(imagePath);
        }
    }
    catch (Exception Ex)
    {
        LogException(Ex);
    }

    return Json("success");
}

Create GUID / UUID in JavaScript

    function generateUUID() {
        var d = new Date().getTime();
        if (window.performance && typeof window.performance.now === "function") {
            d += performance.now();; //use high-precision timer if available
        }
        var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
            var r = (d + Math.random() * 16) % 16 | 0;
            d = Math.floor(d / 16);
            return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16);
        });
        return uuid;
    };

 var guid = generateUUID();

Taken from a question from stackoverflow.com-
http://stackoverflow.com/questions/105034/create-guid-uuid-in-javascript

Auto complete search textbox like google in a simple & easy way.

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>AutoComplete Box with jQuery</title>
    <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/themes/base/jquery-ui.css" rel="stylesheet" type="text/css" />
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/jquery-ui.min.js"></script>
    
</head>
<body>
    <div class="demo">
        <div class="ui-widget">
            <label for="tbAuto">Enter UserName: </label>
            <input type="text" id="txtSearch" class="autosuggest" style="width:300px;" />
        </div>
        </div>
</body>
</html>

Place the script in head tag

<script type="text/javascript">
        $(document).ready(function () {
            SearchText();
        });
        function SearchText() {
            $(".autosuggest").autocomplete({
                source: function (request, response) {
                    $.ajax({
                        type: "POST",
                        contentType: "application/json; charset=utf-8",
                        url: "/Home/GetAutoCompleteData",
                        data: "{'username':'" + document.getElementById('txtSearch').value + "'}",
                        dataType: "json",
                        success: function (data) {
                            response(data.d);
                        },
                        error: function (result) {
                            alert("Error");
                        }
                    });
                }
            });
        }
    </script>
    public class HomeController : Controller
    {
        //
        // GET: /Home/
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult GetAutoCompleteData(string username)
        {

            List<string> result = new List<string>();

            result.Add("Hello");
            result.Add("World");
            return Json(new { d = result }, JsonRequestBehavior.AllowGet);
        }
    }

Working with HTML data- attribute

Sample HTML –

 
<td class="areaCell" data-expandstatus="false">Some text</td>

JQuery part –

 
//getter
var expandstatus = currentRow.attr('data-expandstatus');
//setter
currentRow.attr("data-expandstatus", "true"); 

//Or
//getter
var expandstatus = $(this).data('expandstatus');
//setter
//Functionable setter not found.

Lazy Load on scroll – Complete example

<!--HTML part -->
<div class="container" id="container">
</div>
//JQuery Part- 
$(function() {
  //--> Handle window scroll event
  $(window).scroll(function () {
     //jQuery scrollTop function will return the area hidden on the top of the page.
     var CurrentScroll = $(this).scrollTop(); 
     //detect scroll down or up
     if (CurrentScroll > LastScroll) {
        //Code for down-ward scrolling (scroll bar going to down).
        var diff = CurrentScroll - scrollAmount;
        //Let user scroll at least 200px
        if (diff >= 200) {
           LoadMorePosts();
           scrollAmount = CurrentScroll;
        }
     }
     else {
       //up-ward scrolling
       scrollAmount = 0;
     }
     //Updates last scroll position
     LastScroll = CurrentScroll;
   });
   //<-- Handle window scroll event


    //--> AJAX call to laod posts in lazy style
    function LoadMorePosts() {
        var fd = new FormData();
        fd.append("PageCount", pageCount);
        $.ajax({
            url: '/Home/GetNextPosts?sid=' + '@ViewBag.SID',
            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) {
                if (response.Complete == 'yes') {
                    pageCount++;
                    var posts = response.Posts;
                    if (posts.length>0) {
                        $.each(posts, function () {
                            $('#container').append('<div class="row"> <div class="col-lg-12"><h2>' + this.PostTitle + '</h2></div></div>');
                        });
                    }
                }
                else {
                }
            },
            error: function (request, status, error) {
            },
            complete: function () {
            }
        });
    }
    //<----AJAX call to laod posts in lazy style

});

ASP.NET MVC Controller Code (C#)-

public class HomeController : Controller
{
   public JsonResult GetNextPosts(FormCollection data)
   {
      int pageCount = Convert.ToInt32(data["PageCount"]);
      List<BlogPost> posts = BlogContentManager.GetPosts(null, pageCount);
      return Json(new{Complete="yes", Posts= posts}, JsonRequestBehavior.AllowGet);
   }
}

Data Access Layer (Model)

public static List<BlogPost> GetPosts(Int32? categoryId,int pageCount)
{
    List<BlogPost> contents = new List<BlogPost>();

    //Return next 5 posts
    int startNumber = (pageCount * 5) + 1;
    int endNumber = (pageCount * 5) + 5; 

    using (SqlConnection connection = new SqlConnection(ConnectionString))
    {
        string sqlSelect = String.Empty;
        if (categoryId == null)
        {
            sqlSelect = @"  SELECT PostId,PostTitle,PostContent,CategoryId,CategoryName, PublishDateTime
                            FROM
	                            (
		                            SELECT ROW_NUMBER() OVER( ORDER BY dbo.BlogPosts.PostId DESC ) AS row, dbo.BlogPosts.PostId, dbo.BlogPosts.PostTitle, dbo.BlogPosts.PostContent, dbo.BlogPosts.CategoryId, dbo.Category.CategoryName, dbo.BlogPosts.PublishDateTime
		                            FROM dbo.Category INNER JOIN dbo.BlogPosts ON dbo.Category.CategoryId = dbo.BlogPosts.CategoryId
	                            )
                            AS data WHERE row BETWEEN "+ startNumber +" AND "+ endNumber +" ORDER BY PostId DESC";
        }
        else
        {
            sqlSelect = @"  SELECT PostId,PostTitle,PostContent,CategoryId,CategoryName, PublishDateTime
                            FROM
	                            (
		                            SELECT ROW_NUMBER() OVER( ORDER BY dbo.BlogPosts.PostId DESC ) AS row, dbo.BlogPosts.PostId, dbo.BlogPosts.PostTitle, dbo.BlogPosts.PostContent, dbo.BlogPosts.CategoryId, dbo.Category.CategoryName, dbo.BlogPosts.PublishDateTime
		                            FROM dbo.Category INNER JOIN dbo.BlogPosts ON dbo.Category.CategoryId = dbo.BlogPosts.CategoryId where dbo.BlogPosts.CategoryId="+ categoryId + @"
	                            )
                            AS data WHERE row BETWEEN " + startNumber + " AND " + endNumber + " ORDER BY PostId DESC";
        }

        using (SqlCommand command = new SqlCommand(sqlSelect, connection))
        {
            connection.Open();
            using (SqlDataReader reader = command.ExecuteReader(CommandBehavior.CloseConnection))
            {
                while (reader.Read())
                {
                    contents.Add(FillEntity(reader));
                }

                if (!reader.IsClosed)
                {
                    reader.Close();
                }
            }
        }
    }

    return contents;
}

HTML Checkbox Tips and Tricks

//Checkbox checked change event handler
$('#CheckBox').click(function () 
{
    var thisCheck = $(this);

    if (thisCheck.is(':checked')) 
    {
       $('#span2').hide();
    }
    else
    {
       $('#span2').show();
    }
});

//Get checkbox value (checked/unchecked)
var checkBoxValue = $('#CheckBox').is(':checked');

HTML Select/Combo/DropDown tips and tricks

<select id="combo">
   <option value="1">One</option>
   <option value="2">Two</option>
</select>
<script>
   $(function () {
      var $Combo= $('#combo'); // assign to a variable

     //Get selected text 
         var selectedText = $('#combo>option:selected').html();
         //or,
         var selectedText = $('#combo option:selected').html(); 

      //Get selected value 
          var selectedVal = $('#combo>option:selected').attr('value');
          //or,    
          var selectedVal = $('#combo option:selected').attr('value');
      
         var selectedVal = $('#combo>option:selected').val();
         var selectedVal = $('#combo option:selected').val();

         var selectedVal = $($Combo, 'option:selected').attr('value');
         var selectedVal = $($Combo, 'option:selected').val();

      //Handle change event
      $regionCombo.change(function () {
                 //code to further...
             });
      });

      
     //Manipulate Selected Index (It cant be done with jquery)
     var $Combo = document.getElementById('combo');
     var selectedIndex = $Combo.selectedIndex; //getting selected index
     $Combo.selectedIndex = 2; //setting selected index

</script>