Quickly submit HTML Form in AJAX as JSON

//
//JQuery part-
//
function form_to_json(selector) {
    var ary = $(selector).serializeArray();
    var obj = {};
    for (var a = 0; a < ary.length; a++) obj[ary[a].name] = ary[a].value;
    return obj;
}

$('#SubmitTheForm').click(function (e) {
    e.preventDefault();
    var $button = $(this);
    var url = $('#form').attr("action");
    var formdata = form_to_json('#form');
    $.ajax({
        type: 'POST',
        url: url,
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify(formdata), 
        dataType: 'json',
        beforeSend: function () {
            $button.attr('disabled', 'disabled');
            $button.html('Working…');
        },
        success: function (result) {
            console.log(result);
        },
        error: function (request, status, error) {
            alert('Failed to save. Error Details – Request: ' + request + ', Status: ' + status + ', Error: ' + error);
        },
        complete: function () {
            $button.removeAttr('disabled');
            $button.html('Submit');
        }
    });
});
//
//JQuery part-
//
public ActionResult AddBr(int Id, string Name)
{
    return Json(BrName);
}
Advertisements

Quickly submit HTML Form in AJAX

It is best for quickly submit a simple html form via AJAX.

//
//JQuery Part
//
$('#SubmitTheForm').click(function (e) {
    e.preventDefault();
    var $button = $(this);
    var SubmitURL = $('#form').attr("action");
    var FormData = $('#form').serialize();
    $.ajax({
        type: 'POST',
        url: url,
        data: FormData,
        beforeSend: function () {
            $button.attr('disabled', 'disabled');
            $button.html('Working…');
        },
        success: function (result) {         
        },
        error: function (request, status, error) {
        },
        complete: function () {
            $button.removeAttr('disabled');
            $button.html('Submit');
        }
    });
});
//
//C# Part
//
[HttpPost]
public ActionResult AddBr(int id, string name)
{
    return Json("success");
}

Convert HTML Form to JSON


Option -1:
function form_to_json(selector) {
    var ary = $(selector).serializeArray();
    var obj = {};
    for (var a = 0; a < ary.length; a++) obj[ary[a].name] = ary[a].value;
    return obj;
}

//Example
var mydata = form_to_json('#form');
JSON.stringify(mydata);
---------------------------------------------------------

Option-2:
Using Third party JQuery plugin- http://maxatwork.github.io/form2js/

<script src="form2js.js"></script>
<script src="jquery.toObject.js"></script>

var data = $('#form').toObject({skipEmpty:false});
JSON.stringify(data)

Custom Attribute in C#

public class MyCustomAttribute : Attribute
{
    public bool IgnoreIt { get; set; }
    public string FormatString { get; set; }
}

public class Student
{
    [MyCustom(FormatString = "hello", IgnoreIt = false)]
    public string Name { get; set; }

    [MyCustom(IgnoreIt = true)]
    public string Id { get; set; }
}

// Directly check for specific attribute (i.e. FormatString) in specific property 
// (i.e. Name)

var formatString = AttributeHelper.GetPropertyAttributeValue<Student, string, MyCustomAttribute, string>(prop => prop.Name, attr => attr.FormatString.ToString());

public static class AttributeHelper
{
    public static TValue GetPropertyAttributeValue<T, TOut, TAttribute, TValue>(
        Expression<Func<T, TOut>> propertyExpression,
        Func<TAttribute, TValue> valueSelector)
        where TAttribute : Attribute
    {
        var expression = (MemberExpression)propertyExpression.Body;
        var propertyInfo = (PropertyInfo)expression.Member;
        var att = propertyInfo.GetCustomAttributes(typeof(TAttribute), true).FirstOrDefault() as TAttribute;
        return att != null ? valueSelector(att) : default(TValue);
    }
}

//Dynamically check attribute and it's value
PropertyInfo[] props = typeof(Student).GetProperties();
foreach (PropertyInfo prop in props)
{
    var attribute = prop.GetCustomAttributes(typeof(MyCustomAttribute), true).FirstOrDefault() as MyCustomAttribute;
    if (attribute != null)
    {
        if (attribute.FormatString == null)
        {
            Console.WriteLine("null");
        }
        else
        {
            Console.WriteLine(attribute.FormatString);
        }
    }
}

Add New Style To Google Docs

In order to enable it you need to create a new script: Tools >> Script Editor>> New and paste the code there. Then you will have to authorize the script and reload the document so that the menu appears on in the menu bar. Then select a patch of text and pick Extras >> Apply code style. The following code snippet was taken from here- http://pastebin.com/4pNBJ9pC

// is called by google docs when a document is open
// adds a menu with a menu item that applies a style to the currently selected text
function onOpen() {
  DocumentApp.getUi()
  .createMenu('Extras')
  .addItem('Apply code style', 'applyCodeStyle')
  .addToUi();
}
 
// definition of a style to be applied
var style = {
  bold: false,
  backgroundColor: "#DDDDDD",
  fontFamily: DocumentApp.FontFamily.CONSOLAS
};
 
// helper function that strips the selected element and passes it to a handler
function withElement(processPartial, processFull) {
  var selection = DocumentApp.getActiveDocument().getSelection();
  if (selection) {
    var elements = selection.getSelectedElements();
    for (var i = 0; i < elements.length; i++) {
      var element = elements[i];
      if (element.getElement().editAsText) {
        var text = element.getElement();
        if (element.isPartial()) {
          var from = element.getStartOffset();
          var to = element.getEndOffsetInclusive();
          return processPartial(element, text, from, to);
        } else {
          return processFull(element, text);
        }
      }
    }
  }
}
 
// called in response to the click on a menu item
function applyCodeStyle() {
  return withElement(
    applyPartialStyle.bind(this, style),
    applyFullStyle.bind(this, style)
  );
}
 
// applies the style to a selected text range
function applyPartialStyle(style, element, text, from, to) {
  text.setFontFamily(from, to, style.fontFamily);
  text.setBackgroundColor(from, to, style.backgroundColor);
  text.setBold(from, to, style.bold);
}
 
// applies the style if the entire element is selected
function applyFullStyle(style, element, text) {
  text.setFontFamily(style.fontFamily);
  text.setBackgroundColor(style.backgroundColor);
  text.setBold(style.bold);
}

WebRequest From WinForm Application

private void btnSave_Click(object sender, EventArgs e)
{
    try
    {

        btnSave.Enabled = false;

        String filePath = txtVoiceFileName.Text;

        // Create a request using a URL that can receive a post. 
        WebRequest request = WebRequest.Create("http://182.161.999.111:2022/Home/ReceiveAudio/");
        // Set the Method property of the request to POST.
        request.Method = "POST";
        // Create POST data and convert it to a byte array.
        // string postData = "This is a test that posts this string to a Web server.";


        NameValueCollection outgoingQueryString = HttpUtility.ParseQueryString(String.Empty);
        outgoingQueryString.Add("CustomerName", txtCustomerName.Text.Trim() );
        outgoingQueryString.Add("ContactNumber", txtMsisdn.Text.Trim());
           


        string postData = outgoingQueryString.ToString();

        byte[] byteArray = Encoding.UTF8.GetBytes(postData);
        // Set the ContentType property of the WebRequest.
        request.ContentType = "application/x-www-form-urlencoded";
        // Set the ContentLength property of the WebRequest.
        request.ContentLength = byteArray.Length;
        // Get the request stream.
        Stream dataStream = request.GetRequestStream();
        // Write the data to the request stream.
        dataStream.Write(byteArray, 0, byteArray.Length);
        // Close the Stream object.
        dataStream.Close();
        // Get the response.
        WebResponse response = request.GetResponse();
        // Display the status.
        Console.WriteLine(((HttpWebResponse)response).StatusDescription);
        // Get the stream containing content returned by the server.
        dataStream = response.GetResponseStream();
        // Open the stream using a StreamReader for easy access.
        StreamReader reader = new StreamReader(dataStream);
        // Read the content.
        string responseFromServer = reader.ReadToEnd();
        // Display the content.
        Console.WriteLine(responseFromServer);
        MessageBox.Show(responseFromServer);
        // Clean up the streams.
        reader.Close();
        dataStream.Close();
        response.Close();

        // String filePath = txtVoiceFileName.Text;
        var FileUploadResponse = WebHelper.MakeRequest("http://182.160.99.115:2022/Home/UploadAudio/",
                            new
                            {
                                wavFile = new FileInfo(filePath)
                                //Test = "Hello"
                                //File1 = new UploadFile(@"text\plain", "file1.txt", new MemoryStream(Encoding.UTF8.GetBytes("Hello World"))),
                                //File2 = new FileInfo("MyFile.txt")
                            });
        var FileUploadResult = FileUploadResponse.ResultToString();

    }
    catch (Exception Ex)
    {
        MessageBox.Show(Ex.Message);                
    }
    finally { btnSave.Enabled = true; }
}



//===============================================

[HttpPost]
public JsonResult ReceiveAudio(FormCollection data)
{
    try
    {
        string CustomerName = data["CustomerName"].ToString();
        string ContactNumber = data["ContactNumber"].ToString();
        string IsNewSimActivation = data["IsNewSimActivation"].ToString();
        string IsSimReplacement = data["IsSimReplacement"].ToString();
        string IsRv = data["IsRv"].ToString();
        string IsDataActivation = data["IsDataActivation"].ToString();
        string IsDeviceOffers = data["IsDeviceOffers"].ToString();
        string IsVas = data["IsVas"].ToString();
        string IsCampMsg = data["IsCampMsg"].ToString();
        string CashReceived = data["CashReceived"].ToString();
        string IsEasyLoad = data["IsEasyLoad"].ToString();
        string VoiceFileName = data["VoiceFileName"].ToString();

        string ConnectionString = WebConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;

           

        return Json("Success");
    }
    catch (Exception Ex)
    {
        return Json("Server says:" + Ex.Message, JsonRequestBehavior.AllowGet);

    }
}

Configure ASP.NET MVC To Accept Large File Uploading

///
///In Web.config
///

<configuration>
    <appSettings>
       ...
    </appSettings>
  

    <system.web>
        <compilation debug="true" targetFramework="4.5"/>
        <httpRuntime targetFramework="4.5"
                     executionTimeout="1000"
                     maxRequestLength="214748364"
                     useFullyQualifiedRedirectUrl="false"
                     minFreeThreads="8"
                     minLocalRequestFreeThreads="4"
                     appRequestQueueLimit="100" />
    </system.web>

    <system.webServer>
        <validation validateIntegratedModeConfiguration="false" />
        <handlers>
            <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
            <remove name="OPTIONSVerbHandler" />
            <remove name="TRACEVerbHandler" />
            <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
        </handlers>

        <security>
            <requestFiltering>
                <requestLimits maxAllowedContentLength="1073741824" />
            </requestFiltering>
        </security>
    </system.webServer>

    <connectionStrings>
        ....
    </connectionStrings> 
</configuration>
///
/// In Controller
///

[ValidateInput(false)]
[HttpPost]
public JsonResult UploadAudio()
{
    try
    {
        foreach (string f in Request.Files.AllKeys)
        {
            var file = Request.Files[f];

            var path = HttpContext.Server.MapPath("~/Voices");
            if (!System.IO.File.Exists(System.IO.Path.Combine(path, file.FileName)))
            {
                file.SaveAs(System.IO.Path.Combine(path, file.FileName));
            }
        }

        return Json("success");
    }
    catch (Exception Ex)
    {
        return Json("Server says:" + Ex.Message, JsonRequestBehavior.AllowGet);
    }
}

ASP.NET MVC RedirectToAction() With Query String

public ActionResult Index()
{
    //If no area
    return RedirectToAction("ActionMethod", "Controller", new { userid=5, name="Five"}); 

   //If area
    return RedirectToAction("ActionMethod", "Controller", new { area = "AreaName", userid = 5, name = "Five" });

}


//Redirected Action Method
public ActionResult Index(int userid, string name)
{
    return View();
}

//OR
public ActionResult Index()
{
    int userId  = Convert.ToInt32(Request.QueryString["userid"]);
    String name = Request.QueryString["name"];
    return View();
}