Binding Bootstrap Dual ListBox with ASP.NET MVC

I have use duallist box from http://www.virtuosoft.eu/code/bootstrap-duallistbox/  to populate list of staff entity from controller that come back from a json request.

To load unselected and selected staff at the same time and display the unselected staff on the left side of dual listbox while selected one on right side.

In html:

 <select id="dualList" class="dualList" multiple="multiple" name="staffIds" size="10"></select>

In content:

 <%: Styles.Render( <%: Styles.Render( "~/Content/plugins/duallistbox/bootstrap-duallistbox.css" ) %>

In Script:

function initDualList(TRId) {
 $.ajax({
  url: "/RepresentativeAssignment/ListStaff/",
  type: "POST",
  data: { Id: Id},
  dataType: "json"
 }).then(querySuccess);

function querySuccess(data) {
   $(".dualList").html();
   $.each(data, function (index, value) {
    if (TRId.length == 0) {
    var option = $("").val(value.Id).text(value.StaffCode + " - " + value.StaffName);
    } else {
    if (value.StaffCode.indexOf("UnSelected-") >= 0) {
     var staffCodeStr = value.StaffCode.substring(11, value.StaffCode.length);
     var option = $("").val(value.Id).text(staffCodeStr + " - " + value.StaffName);
    }else{
     var option = $("").val(value.Id).text(value.StaffCode + " - " + value.StaffName).attr("selected", "selected");
    }
   } 
   $(".dualList").append(option);
  });

  $('.dualList').bootstrapDualListbox({
   preserveselectiononmove: 'moved',
   moveonselect: false
  });

  //remove 'moveall' and 'removeall' button in the dual listbox
  $('#dualList').parent().find('.moveall').css('display', 'none');
  $('#dualList').parent().find('.removeall').css('display', 'none');
 }
}

In Controller:

[HttpPost]
 public string ListStaff(long? staffId)
 {
   List listofStaff = new List();
   if (TRId == null)
   {
     listofStaff = SystemSeg.getAllActiveStaffNotUseInAssignmentMap();
    }
    else
    {
       var RepresentativeList = SystemSeg.getById((long)staffId);
        var AssignmentBaseOnCodeList =SystemSeg.getAllRepresentativeAssignmentMapByCode(RepresentativeList.Code);

        var AllActiveStaffNotUseInAssignmentMapList = SystemSeg.getAllActiveStaffNotUseInAssignmentMap();

         //Rest of Active Staff to be display on the left side of the duallist
         for (int i = 0; i < AllActiveStaffNotUseInAssignmentMapList.Count; i++)
         {
             User staff = SystemSeg.GetUserById(AllActiveStaffNotUseInAssignmentMapList[i].Id);
              staff.UserCode = "UnSelected-" + staff.StaffCode;
              listofStaff.Add(staff);
          }
    }
    return WebUtil.Serialize(listofStaff);
 }

Return PDF/TXT/XLS/PXLS to browser in ASP.NET MVC using crystal report

This example is using SAP crystal report for Visual studio. Can get a copy here for free.

Below sample show how to generate different file type format report to the browser dynamically.

 

In Controller:

public ActionResult PrintReport(string filters, string fileType)
 {
  var page = FilterPage(new Page<StaffOrder>(), filters);

  report = ReportUtil.GetReport<StaffOrder, StaffOrderReport>(StaffOrderModel.PropertyNames, page.result.OrderBy(x => x.StaffName).ThenBy(z => z.Id).ToList());
  ReportUtil.AssignBasicInfo(report, "Staff Order Report", WebUtil.GetUserDetails().username);

  return ReportUtil.GenerateReport(report, fileType);

 }

 

In ReportUtil class:

using System.Globalization;
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Web.Mvc;
using Microsoft.Office.Interop.Excel;

namespace STDSInternal
{
 public class ReportUtil
 {
 public static TK GetReport<T, TK>(string[] names, IList<T> items)
 where T : class
 where TK : ReportClass, new()
 {
 var report = new TK();
 report.Load();
 report.SetDataSource(GetDataTable<T>(names, items));
 return report;
 }
public static System.Data.DataTable GetDataTable<T>(string[] names, IList<T> items)
{
 var dt = new System.Data.DataTable();
 dt.Columns.AddRange(GetDataColumns(names));
 foreach (T item in items)
 {
 var objs = new List<object>();
 foreach (var name in names)
 {
 PropertyInfo pi = item.GetType().GetProperty(name);
 var obj = pi.GetValue(item);
 objs.Add(DoConversion(obj));
 }
 dt.Rows.Add(objs.ToArray());
 }
 return dt;
 }

public static DataColumn[] GetDataColumns(string[] columnNames)
 {
 return columnNames.Select(name => new DataColumn(name)).ToArray();
 }

public static FileStreamResult GenerateReport<T>(T report, string fileType) where T : ReportClass
 {
 var contentType = WebConstants.APPLICATION_PDF;
 switch (fileType)
 {
 case "txt":
   report.ExportOptions.ExportFormatType = ExportFormatType.Text;
   contentType = WebConstants.TEXT_PLAIN;
   break;
 case "xls":
   report.ExportOptions.ExportFormatType = ExportFormatType.Excel;
   contentType = WebConstants.TEXT_XLS;
   break;
 case "pxls":
   report.ExportOptions.ExportFormatType = ExportFormatType.ExcelRecord;
   contentType = WebConstants.TEXT_XLS;
   fileType = "xls";
   break;
 default:
   report.ExportOptions.ExportFormatType = ExportFormatType.PortableDocFormat;
   fileType = "pdf";
   break;
 }
 return new FileStreamResult(report.ExportToStream(report.ExportOptions.ExportFormatType), contentType)
 {
 FileDownloadName = report.SummaryInfo.ReportTitle + "." + fileType
 };

}

 

In WebConstants class file:

public static readonly string APPLICATION_PDF = "application/pdf";
public static readonly string TEXT_PLAIN = "text/plain";
public static readonly string TEXT_XLS = "text/xls";

 

 

 

 

 

Making a Simple Ajax call to controller in asp.net mvc to load data into dropdownlist

Controller:

 Public Function Get_Plant() As ActionResult
 Dim plantrole As New PlantRequestParam
 Dim rinfo = New Common.ResultInfo
 rinfo = iPlant.GetAllActiveList(plantrole)
 Return Json(rinfo)
End Function

View:

var AjaxUrl = "../Home/Get_Plant";
$.ajax({
 type: 'POST',
 url: AjaxUrl,
 contentType: 'application/json; charset=utf-8',
 success: function (data) {
 if (data.Status == true) {
 var taglist = data.Data;

$.each(taglist, function (index, value) {
 var opt = new Option(value.Name, value.Id);
 $(opt).attr('data-code', value.Code);
 $('#PlantDdl').append(opt);
 });

error: function (ex) {
 showAlert({
 Message: AjaxUrl + "
" + ex.status + " - " + $(ex.responseText).filter('title').text(),
 Status: false
 });
 });

To load into HTML li tag:

$.each(taglist, function (index, value) {
 list.append(' + value.Code + ');
 });

 

 

jhep-coursera-course4.pngHTML, CSS, and Javascript for Web Developers

Finally! The Result!

At last! Waited for ages the exam results and now they’re out! I have pass all my subjects and completed all the modules for my MBA course. I am free to graduate!

result

Follow by this is to get a job related to what I’ve studied. But finding the job which is related is tough, mostly experience one’s will get the job instead of the fresh graduate. I guess I have to put more effort in my job and family.

 

Load XML into Database

Load xml file into store procedure to insert into table.

Sample xml file:

<?xml version='1.0' encoding='UTF-8' ?>
<FctTypes>
 <reportType>SSS</reportType>
 <tradingDate>01-Jun-2017</tradingDate>
 <period>1</period>
 <Details>
   <facilityType>AAA</facilityType>
   <grossInjection>111.11</grossInjection>
   <netInjection>222.22</netInjection>
 </Details>
 <Details>
   <facilityType>BBB</facilityType>
   <grossInjection>333.33</grossInjection>
   <netInjection>555.55</netInjection>
 </Details>
 <Details>
   <facilityType>CCC</facilityType>
   <grossInjection>122.11</grossInjection>
   <netInjection>244.22</netInjection>
 </Details>
</FctTypes>
<FctTypes>
 <reportType>SSS</reportType>
 <tradingDate>01-Jun-2017</tradingDate>
 <period>2</period>
 <Details>
   <facilityType>AAA</facilityType>
   <grossInjection>111.11</grossInjection>
   <netInjection>222.22</netInjection>
 </Details>
 <Details>
   <facilityType>BBB</facilityType>
   <grossInjection>333.33</grossInjection>
   <netInjection>555.55</netInjection>
 </Details>
 <Details>
   <facilityType>CCC</facilityType>
   <grossInjection>122.11</grossInjection>
   <netInjection>244.22</netInjection>
 </Details>
</FctTypes>

In database store procedure:

@strMG01 contain the string of content in xml file which pass from the application.

DECLARE @docHandle INT
DECLARE @xml XML = @strMG01

 CREATE TABLE #TempMG01(
 [Period] [smallint] NULL,
 [ReportType] [varchar](2) NULL,
 [TradingDate] [datetime] NULL,
 [FacilityType] [varchar](60) NULL,
 [GrossInjection] [varchar](60) NULL,
 [NetInjection] [varchar](60) NULL
 )

 INSERT INTO #TempMG01

 SELECT 
 a.Period,
 a.ReportType,
 a.TradingDate,
 a.FacilityType,
 a.GrossInjection,
 a.NetInjection
 FROM(

 SELECT 
 tbl.TempMG01.value('reportType[1]', 'VARCHAR(2)') ReportType,
 tbl.TempMG01.value('tradingDate[1]', 'DATETIME') TradingDate,
 tbl.TempMG01.value('period[1]', 'smallint') Period,
 i.pd.value('facilityType[1]', 'VARCHAR(60)') FacilityType,
 i.pd.value('grossInjection[1]','VARCHAR(60)') GrossInjection,
 i.pd.value('netInjection[1]','VARCHAR(60)') NetInjection
 FROM @xml.nodes('//FctTypes') AS tbl(TempMG01)
 CROSS APPLY @xml.nodes('//FctTypes/Details') AS i(pd)
 ) a

after this you can just insert it into the table you intended with a insert statement.

Sample inserted record as below:

Untitled.jpg

 

Authorization failure for Ajax request in MVC application

I encounter an ajax request authorization failure and causes bad user experience. I had click on a button which require ajax response in my ASP.net MVC application which already timout. Below is the way to handle it properly without getting any bugs.

I have created a OnAuthorizationModule action filter to check on each action to determine which pipeline to go. If IsAjaxRequest is true, it will throw HttpException, else it will redirect to error page.

 

ajax1

JQuery global error handle will receive the exception and display error message accordingly.

ajax2

 

ajax3.JPG

Responsive display: Inline-block

How to develop a responsive site which size can be adjusted while the display is still able to maintain its sequence and order, displaying a meaning page without running out of order?

Basically just have to add an attribute in the style of the div tag will do. For the main div, add display:inline-block in style, while the div’s in the main div will have to add float:left in style. While all the UI controls, images, words are in div tag.

div

 

An example from below which I have tried:

Normal web page view

before

Smaller size web page view (mobile)

after

 The code for above UI: Responsive display Inline-block

Web site for own testing:jsfiddle

 

 

A help in sharing how you feel after coming to my blog

Hi All,

I’m just trying to do a simple survey to see where I can improve to make my blog a better one. I do welcome if you have any comment whether good or bad or constructive criticism, please post below in the reply section. It would be better to specify which area can be improve. Thanks. 🙂