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);
 }

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('<li data-id="' + value.Id + '" data-name="' + value.Name + '" data-predictionperformance="'
 + value.PredictionPerformanceIndicator + '"><a>' + value.Code + '</a></li>');
 });

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

Simple way of adding a row of textboxes dynamically for input

How to add a row of column dynamically when user click the link to add new row?

Below illustration were done in MVC framework whereby as it is not as easy as using the control directly in web form. These concerns are populate data into the drop down list, passing back all newly added data to the controller and retrieving all data for display when page load.

dynamicAdd

In my view page, I have added the below code.

dynamicAdd2In script section, I have added a few function calls in document.ready. when page load, those method will be trigger.

dynamicAdd3In initRelationship(), is to retrieve stored values to be display in the textboxes. The first ajax postback is to retrieve a list of objects of data to be display and second ajax postback is to retrieve a list of relationship type to be display in the dropdownlist. After that, it will loop through the list of relationship type to check which one is the selected one based on the data get from list of objects. After that, all the options will be added to a string of HTML code to be appended to the div tag.

dynamicAdd6When ‘add another account’ link is click, below code will be trigger to add a new row. I have used ajax to get the list of relationship type to added to dropdownlist options before append the string of HTML code to the div tag.

dynamicAdd4Below method is just solely to assigned values to the rows of textboxes if anything left out populated into the UI controls. Can ignore this is above have done it.dynamicAdd5How to pass all these data back to the controller to be process? For all the UI controls above, the name must be the same eg. p_Relationship, p_Relationship[1]…in array format. It will automatically populated into the list in the model.

dynamicAdd7

 

When it post back to controller, you will get all the data to be process!! dynamicAdd8