Generic ajax POST and GET method in MVC and Jquery

//POST method
var ACTIVE_REQ_CNT = 0;
function fnCallAjaxHttpPostEvent(url, postData, isAsync, showLoader, successCallback) {
 var args = Array.prototype.slice.call(arguments).slice(5);
 return $.ajax({
 async: isAsync,
 type: "POST",
 contentType: "application/json",
 url: url,
 cache: false,
 data: JSON.stringify(postData),
 beforeSend: function () {
 if (showLoader) {
 ACTIVE_REQ_CNT++;
 fnShowWaitImage();
 }
 },
 success: function (data, textStatus, jqXHR) {
 if (fnScanResponseForSessionTimeOut(jqXHR)) {
 fnSessionTimeOutHandler();
 } else {
 var callbackArgs = [];
 callbackArgs.push(data)
 callbackArgs = callbackArgs.concat(args);
 try {
 successCallback.apply(this, callbackArgs);
 } catch (ex) {
 console.error(ex);
 }
 }
 },
 failure: function (response) {
 console.error(response);
 },
 complete: function () {
 if (showLoader) {
 ACTIVE_REQ_CNT--;
 ACTIVE_REQ_CNT === 0 && fnHideWaitImage();
 }
 }
 });
}



//How to use POST method 
fnCallAjaxHttpPostEvent('@Url.Action("ActionName", "ControllerName")', paramModel , true, true, fnSaveSuccess, popupObj);

function fnSaveSuccess(data, popupObj) {
}

Here, popupObj is the extra parameter that can be fetched in successCallback function.



//GET method
var ACTIVE_REQ_CNT = 0;
function fnCallAjaxHttpGetEvent(url, param, isAsync, showLoader, successCallback) {
 var args = Array.prototype.slice.call(arguments).slice(5);
 return $.ajax({
 async: isAsync,
 type: "GET",
 contentType: "application/json",
 url: url,
 cache: false,
 data: param,
 beforeSend: function () {
 if (showLoader) {
 ACTIVE_REQ_CNT++;
 fnShowWaitImage();
 }
 },
 success: function (data, textStatus, jqXHR) {
 if (fnScanResponseForSessionTimeOut(jqXHR)) {
 fnSessionTimeOutHandler();
 } else {
 var callbackArgs = [];
 callbackArgs.push(data)
 callbackArgs = callbackArgs.concat(args);
 try {
 successCallback.apply(this, callbackArgs);
 } catch (ex) {
 console.error(ex);
 }
 }
 },
 failure: function (response) {
 console.error(response);
 },
 complete: function () {
 if (showLoader) {
 ACTIVE_REQ_CNT--;
 ACTIVE_REQ_CNT === 0 && fnHideWaitImage();
 }
 }
 });
}


//How to use GET method 

function fnGetData() {
 return fnCallAjaxHttpGetEvent('@Url.Action("ActionName", "ControllerName")', { paramId: paramId}, true, true, fnBindSucessFunction);
 }

function fnBindSuccessFunction(result){
  debugger;
}

Advertisements

Nested If else conditions in Kendo-UI Grid ClientTemplate

Standard Nested If else statement/ syntax used in Kendo-ui Grid

 

columns.Bound(c => c.ItemId)
.ClientTemplate(
“# if (condition-1) { #” +
“# if(condition-2) { #” +
“content-one”
“# } #” +
“#} else { #” +
“# if(condition-2) {#” +
“content-two”
“# } #” +
“# } #”
)

 

There are three ways to use the hash syntax:

  1. Render values as HTML: #= #.
  2. Use HTML encoding to display values: #: #.
  3. Execute arbitrary JavaScript code: # if (true) { # ... non-script content here ... # } #.

C# : Convert model class from database table using stored procedure

declare @TableName sysname = 'TableName'
declare @Result varchar(max) = 'public class ' + @TableName + '
{'

select @Result = @Result + '
    public ' + ColumnType + NullableSign + ' ' + ColumnName + ' { get; set; }
'
from
(
    select 
        replace(col.name, ' ', '_') ColumnName,
        column_id ColumnId,
        case typ.name 
            when 'bigint' then 'long'
            when 'binary' then 'byte[]'
            when 'bit' then 'bool'
            when 'char' then 'string'
            when 'date' then 'DateTime'
            when 'datetime' then 'DateTime'
            when 'datetime2' then 'DateTime'
            when 'datetimeoffset' then 'DateTimeOffset'
            when 'decimal' then 'decimal'
            when 'float' then 'float'
            when 'image' then 'byte[]'
            when 'int' then 'int'
            when 'money' then 'decimal'
            when 'nchar' then 'string'
            when 'ntext' then 'string'
            when 'numeric' then 'decimal'
            when 'nvarchar' then 'string'
            when 'real' then 'double'
            when 'smalldatetime' then 'DateTime'
            when 'smallint' then 'short'
            when 'smallmoney' then 'decimal'
            when 'text' then 'string'
            when 'time' then 'TimeSpan'
            when 'timestamp' then 'DateTime'
            when 'tinyint' then 'byte'
            when 'uniqueidentifier' then 'Guid'
            when 'varbinary' then 'byte[]'
            when 'varchar' then 'string'
            else 'UNKNOWN_' + typ.name
        end ColumnType,
        case 
            when col.is_nullable = 1 and typ.name in ('bigint', 'bit', 'date', 'datetime', 'datetime2', 'datetimeoffset', 'decimal', 'float', 'int', 'money', 'numeric', 'real', 'smalldatetime', 'smallint', 'smallmoney', 'time', 'tinyint', 'uniqueidentifier') 
            then '?' 
            else '' 
        end NullableSign
    from sys.columns col
        join sys.types typ on
            col.system_type_id = typ.system_type_id AND col.user_type_id = typ.user_type_id
    where object_id = object_id(@TableName)
) t
order by ColumnId

set @Result = @Result  + '
}'

print @Result

Convert DataTable to List in c#

DataTable dt = ‘…some service called to fill this datatable….’
List<DemoModel> demoDetails = new List<DemoModel>();
demoDetails = ConvertDataTable<DemoModel>(dt);

 

public static List<T> ConvertDataTable<T>(DataTable dt)
{
List<T> data = new List<T>();
foreach (DataRow row in dt.Rows)
{
T item = GetItem<T>(row);
data.Add(item);
}
return data;
}

 

private static T GetItem<T>(DataRow dr)
{
Type temp = typeof(T);
T obj = Activator.CreateInstance<T>();

foreach (DataColumn column in dr.Table.Columns)
{
foreach (PropertyInfo pro in temp.GetProperties())
{
if (pro.Name == column.ColumnName)
pro.SetValue(obj, dr[column.ColumnName], null);
else
continue;
}
}
return obj;
}

Missing Microsoft RDLC Report Designer in Visual Studio

Open Control Panel > Programs > Programs and Features

  • Select the entry for your version of Microsoft Visual Studio 2015. In our case, it was Microsoft Visual Studio Enterprise 2015.
  • Click the “Change” button on the top bar above the program list. After the splash screen, a window will open.
  • Press the “Modify” button.
  • Select Windows and Web Development > Microsoft SQL Server Data Tools, and check the box next to it.
  • Press the “Update” button on the lower-right hand side of the window.
  • Once the installation is complete, open your version of Visual Studio. After the new .dll files are loaded, Reporting functionality should be reimplemented, and you should be able to access all related forms, controls, and objects.

get id of closest ‘ul’ or parent id and get value of ‘href’ attribute with Jquery

html:

//if menu is created dynamically it is very useful
<ul id="slider" style="display: none;">
 <li class="panel cloned">test1</li>
 <li class="panel">
  <article>
   <h1><a href="/Admin/RoleMaster"> Role Creation </a> </h1>
  </article>
 </li>
 <li class="panel cloned">test2</li>
</ul>

js:

var url = window.location.pathname; //or window.location.toString();

$('#slider li.panel h1 a').each(function(){
   var myHref= $(this).attr('href');
   if( url == myHref) //compare current url with url value
  {

        var ulId = $(this).closest('ul').attr('id'); //get id of ul tag 
        $("#"+ulId).css("display", "block");
   }
});

asp net mvc : why is html checkbox generating an additional hidden input

I noticed strange behaviour whilst coding and ASP.NET MVC CheckBox Html Helper. I noticed that the field which was in part of a GET form was creating the query string with the same field in it twice. When the box was checked one parameter was true and the other was false.

Say I have a boolean field, MyField, that I am creating a checkbox for. I would write this: @Html.CheckBoxFor("MyField"). You would expect this to output a single check box but if you actually look at the HTML that is generated you will notice that is also creates a hidden field.

<input id="MyField" name="MyField" type="checkbox" value="true">
<input name="MyField" type="hidden" value="false">

 

Solution

Simple solution really. Write the HTML you want in HTML, forget about the HtmlHelper:

1
2
<input type="checkbox" name="MyField" value="true" id="MyField"
@Html.Raw((Model.MyField) ? "checked=\"checked\"" : "") />

Remember the value="true" because the default value to be sent is “on” if it is checked, which obviously can’t be parsed to a Boolean.

Obviously, this doesn’t look that clean but I will continue to do this on forms that use the GET method.