File Upload uisng Jquery in C# ASP.Net MVC

There so many ways to upload files with jqueries in ASP.Net C#. One way is with creating XMLHttpRequest and another way is with FormData object.
In this post i’ll show uploading files and saving form data in one ajax call using jquery.

Upload Files with Jquery in ASP.Net MVC C#

First code for View which represents normal html code of form


@model modelname







File Upload








@Html.TextBoxFor(m => m.File, new { @type = "file", @multiple = "multiple" })





@Html.TextBoxFor(m => m.Field1, new { @class = "form-control datepicker" })
@Html.ValidationMessageFor(m => m.Field1)








MVC Controller Code for Saving File
In controller create action method with two arguments one is for formdata and another one is for List of HttpPostedFileBase Class which represents multiple files that you select.

public JsonResult SaveFilesWithFormData(ModelName FormData, List Of HTTPPostedFileBase Files) //Model Name represents class provided in view
{
try
{
//logic for saving data into database

//save multiple files
foreach (var upload in File)
{
if (upload != null)
{
string pathToSave = "folderpath";

//Check folder is exist or not if not then it will creates folder
if (!Directory.Exists(pathToSave))
{
Directory.CreateDirectory(pathToSave);
}

//get file name for selected file
string filename = Path.GetFileName(upload.FileName);

//save file
upload.SaveAs(pathToSave + filename);
}
}
msg = "Success";
}
catch (Exception ex)
{
Log.Error(ex.Message);
}
return Json(msg, JsonRequestBehavior.AllowGet);
}

Hope that above code will help you to save files easily with form data into server. Keep coding

Display image from byte array in ASP.NET MVC

There are many ways to display image from byte array in MVC as well as normal ASP.Net projects.In this post I’ll explain couple of them.

1) Using BASE64 string of the image through ViewBag 

The first way is by sending a Base64 string as dataURL through ViewBag. As shown in below action method under consideration generates such a Base64 string of the image (often called Data URL) and then pass it to the view via a ViewBag property in MVC.

public ActionResult Image()
{
string path = Server.MapPath("~/images/computer.png");
byte[] imageByteData = System.IO.File.ReadAllBytes(path);
string imageBase64Data=Convert.ToBase64String(imageByteData);
string imageDataURL= string.Format("data:image/png;base64,{0}", imageBase64Data);
ViewBag.ImageData = imageDataURL;
return View();
}

The above code is a action method of Controller. In this action method it uses physical path of image and read all bytes of that image using ReadAllBytes() method. Once it read all bytes of that image in form of byte array,it will converts that byte array into base64 string format.

This converted base64 string is used to generate dataURL as shown in code. Take care of not to forget to append data:image/png;base64 at beginning of base64 string as shown.This way the browser knows that the src attribute value itself contains the image data. and at last assign value of dataURL to ViewBag.and then just below line in View to use that ViewBag.

 

Output :

2) By Sending Image File as ActionResult

In this approach it will reads byte array from image physical path and creates one file, after this it will send that file as result of action method in Controller.

public ActionResult GetImageFile()
{
string path = Server.MapPath("~/images/computer.png");
byte[] imageByteData = System.IO.File.ReadAllBytes(path);
return File(imageByteData, "image/png");
}

To use the GetImageFile() action method you have to write below line in View:

<img src='@Url.Action("GetImageFile", "Home")'/>

Hope this will help you.

C# Currency Converter using Google API

    Currency conversion in C# using Google API

    • There are so many ways to convert amount from one currency to another currency like using google finance converter, Yahoo finance and rate-exchange.
    • In this post i will show conversion using Google Finance Converter.
    • In below code, I create one WebRequest for Google Finance Converter which will return result of arguments which are attached with it.
    • Get the response of WebRequest in form of Stream and stored it in streamReader (which is the object of StreamReader Class).
    • By using, Regex fetched converted amount with desired currency code and stored this result into a string variable and again using Regex fetched only decimal part from generated string.

    Hope this post will help you to get the exact result that you want.


      public string CurrencyConvert(decimal amount, string fromCurrency, string toCurrency)
      {
      decimal currency = 0;
      string convertedAmount = "0";
      try
      {
      string url = string.Format("https://www.google.com/finance/converter?a={2}&from={0}&to={1}", fromCurrency.ToUpper(), toCurrency.ToUpper(), amount);
      WebRequest request = WebRequest.Create(url);
      StreamReader streamReader = new StreamReader(request.GetResponse().GetResponseStream(), System.Text.Encoding.ASCII);
      string result = Regex.Matches(streamReader.ReadToEnd(), "([^<]+)")[0].Groups[1].Value;
      string rs = new Regex(@"^D*?((-?(d+(.d+)?))|(-?.d+)).*").Match(result).Groups[1].Value;
      if (decimal.TryParse((new Regex(@"^D*?((-?(d+(.d+)?))|(-?.d+)).*").Match(result).Groups[1].Value), out currency))
      {
      convertedAmount = currency.ToString("0.00");
      }
      }
      catch (Exception ex)
      {
      throw ex;
      }
      return convertedAmount;
      }

      Allow only numbers in textbox jquery

      • For allowing only numbers in textbox using jQuery, you can create key-press or key-down or key-up event for textbox by using textbox id or class.
      • In below example i used class name (“number”) for applying validation to textbox. 
      • You just had copy above code and paste where you want to apply numeric validation.

      For allowing numbers with decimal points 

      Url rewrite for non-www to www in C#

      • WWW version is very useful to make your web site easily searchable by web crawler also WWW version helps to increase your chances make your web site rank higher in SEO purpose.
      • One common use of URL Rewrite is redirecting http://domain.com to http://www.domain.com.  Many people are doing this for search engine optimization (SEO) so that search engines only see the one site, rather than two sites.  The goal is to set a permanent 301 redirect. 
      • URL Rewrite works at the global level, or site level (or application level for that matter).  Where you apply it is really up to how you manage your server.  Either will work for a domain name redirect like this.
        You can choose to create the rules using IIS Manager, or using a text editor and updating web.config directly.
      • For specifying non-WWW version to WWW version for your web site in C#.net, write below code in web.config inside system.webServer tag,

      MVC CRUD Operations Using jQuery JSON and LINQ To SQL Class

      Step 1 : Database

      Create an EmployeeData table in a SQL database as in the following

      Step 2 : LINQ to SQL class

      Create a LINQ to SQL class to read data from the table as in the following:

      Add Linq to Sql Class

      After using the Server Explorer and adding an EmployeeData table in the surface area as in the following:
      Add Table
      Now add a controller to the CRUD operations for EmployeeData.

      So open the Solution Explorer and right-click on the controller folder and add a controller as in the following:

      Select Controller

      Add Controller Name

      Step 3 : Controller 

      Now create a select controller, an insert controller, an edit controller and a the Delete controller as in the following:

      Step  4 : View

      Now create a view and a partialview on a right-click corresponding to the controller as in the following:
      Add view to controller

      1. Index View (select data)
      Add Index view

      In this figure see the view name is auto create, it’s not changed. After selecting a Template and Model class as shown in the following figure.

      2. Create View (Insert data)
      Create a view to create a partial view .
      Add Create view

      This section also created a script for the model data insert into the table.

      Create View Code


      3. Edit View (Update Employee)
      Also create an Editview as a Partial view.
      Add Edit View

      Edit view code


      In this view also create an update record script as in the following.
      Finally all the operation views are created and can be seen in the project solution. 
      Step: Models

      Now create a Model for EmployeeInfo as in the following:

      Add Models class

      class

      Models Class Code

      Now run your MVC example in a browser.
      Run Application

      Now click the Add New Employee button and insert a record as in the following:
      Add Record

      Now delete the record without 130 with the delete button.
      Record Delete

      Selected Record open with edit dialog

      Press the update button and close the dialog and check the record in the webgrid.
      Record Update

      Add google translator to website

      For adding google language tranlator to your web site click on below link

      Add google translator to website

      Step 1 :  

      • Enter your website url and select default language which you want to apply when your website loads first. 

      Step 2 : 
      • Select languages which you want to use for your website to be translated.You select use all languages or specific languages,
      • Select display mode for language translator display like vertical, horizontal or dropdown only.
      • Based on your requirements select advanced options.
      • Click on Get Code button to get code for translator plugin.

      Plugin Settings
      Step : 3  

      • Copy code from which shown in textbox and paste that code where you want to display translator in your website.
      Plugin Code