Submit JavaScript object to ASP.NET Controller as a model via JQuery-AJAX

JQuery-AJAX
var region = {};
region.RegionId = 1; 
region.RegionName = ‘One’;

var urlData = ‘@Url.Action(“ActionMethod”, “Controller”)’;

$.ajax({
    type: “POST”, url: urlData,
    contentType: “application/json; charset=utf-8”,
    data:   JSON.stringify(region),  
    success: function (result) {
    },
    error: function (request, status, error) {
    }
});

Controller ActionMethod
[HttpPost]
public JsonResult UpdateRegion(Region region)
{
            

}

Model
public class Region
{
    public Int32 RegionId { get; set; }
    public String RegionName { get; set; }

}
Advertisements

Retrieve SCOPE_IDENTITY() value in SQL Server

String sqlInsert = “insert into TableName(colA,ColB) values(@colA,@ColB); select SCOPE_IDENTITY();”;

command.CommandText = sqlInsert;
command.Parameters.Clear();
command.Parameters.AddWithValue(“@colA“, valA);
command.Parameters.AddWithValue(“@colB, valB);

Object autoIdValue = command.ExecuteScalar();

Styling checkbox with CSS

CSS Part

    .checkboxLabel {
        /*display: block;*/
        /*padding-left: 15px;*/
        /*text-indent: -15px;*/
        line-height: 3em;
        vertical-align: middle;
    }

    .checkboxLabel input {
        width: 2.5em !important;
        height: 2.5em !important;
        padding: 15px;
        margin: 0;
        vertical-align: middle;
        position: relative;
        top: -1px;
        *overflow: hidden;
    }


HTML Part
 
         This is a checkbox
 

Parameterized SQL Query

String sql= “INSERT INTO TableName(col1,col2) values(@col1,@col2)”;
SqlCommand command = new SqlCommand();

Option A:
command.Parameters.Add(“@col1“, SqlDbType.VarChar, col1MaxTextLength).Value = “abc”;
command.Parameters.Add(“@col2“, SqlDbType.Int).Value = 123;


Option B:

command.Parameters.AddWithValue(“@col1”, “abc”);
command.Parameters.AddWithValue(“@col2”, 123);

Retrieve object array from FormCollection element in mvc controller

client code================

var products = []

$
('tr').each(function () {
var row = $(this);
var product = {};
product
.Id = row.find('.id').val();
product
.Id = row.find('.quantity').val();
products
.push(product);
});

var data = new FormData();
data
.append('PersonId', pid);
data
.append('SubmitDate', sdate);
data
.append('Products', JSON.stringify(products));

Server code=================

using System.Web.Script.Serialization;

[HttpPost]
public ActionResult SalesData(FormCollection data)
{
String personId=data["PersonId"].ToString();
String submitDate=data["SubmitDate"].ToString();

var serializer = new JavaScriptSerializer();
    var productsStr = data["products"].ToString()
var deserializedProducts = serializer.Deserialize<List<Product>>(productsStr);

}

Query string encryption decryption technique

Encryption Technique
String Id = dtResult.Rows[0][0].ToString();
String dbPassValue = dtResult.Rows[0][2].ToString();
Boolean isPasswordMatched = LoginPassword.Equals(dbPassValue, StringComparison.Ordinal);

if (isPasswordMatched)
{
       String eid = MyCrypto.GetEncryptedQueryString(UserId); //encrypted id
       return Json(new { result = “Redirect”, url = “/Dsr/Home/Index?id=” + Id + “&eid=” + eid });
}

Decryption Technique
if (Request.QueryString[“id”] == null || Request.QueryString[“eid”] == null)
{
      return RedirectToAction(“Index”, “LogIn”, new { area = “Dsr” });
}

String UserId = Request.QueryString[“userid”].ToString();
String encryptedUserId = Request.QueryString[“eid”].ToString();
String userDigest = MyCrypto.GetDecryptedQueryString(encryptedUserId);

            if (!UserId.Equals(userDigest, StringComparison.Ordinal))
            {
                return RedirectToAction(“Index”, “LogIn”, new { area = “Dsr” });
            }


            ViewBag.UserId = UserId; ViewBag.UserIdDigest = encryptedUserIdDigest;

Serialize datatable as JSON

C# Part:

JQuery Part:


using Newtonsoft.Json;




[HttpPost]


public JsonResult GetDatatableAsJson(String currentdate, String cmpositionid)


{


DataTable dt = new DataTable();


//


//Fill datatable as require


//


String SerializedDatatable = JsonConvert.SerializeObject(dt, Formatting.None);


return Json(SerializedDatatable, JsonRequestBehavior.AllowGet);


}



$(function () {


$.ajax({


type: "POST",


url: "CMSupervisor/DateCmSpecificOutletMapData",


async: true,


contentType: "application/json; charset=utf-8",


data: "{'currentdate':'" + currentdate + "','cmpositionid':'" + cmpositionid + "'}",


dataType: 'json',


success: function (data) {


var parsed = JSON.parse(data);


//Looping the Datatable


parsed.forEach(function (row) {


//access the column name


var value = row.ColumnName;


});


}


});


});