Thursday, 24 March 2016

Set DropdownList Selected Value from Hidden Field


Aim :- Set DropdownList Selected Value from Hidden Field. I have added complexity that the dropdownlist id is dynamically generated as it may be necessary to generate the same controls in the page multiple times.

So let’s see what we have here.

Partial view Page
Part of the view content will come from a Partial Page. The Partial Page may be called multiple times (repeated in main view). Hence the hidden field has id/name generated dynamically

@Html.Hidden("SelectedCls"+session.Recipient.RecipientId.ToString(), selectedClass.ClassId)

View Page
The Dropdownlist may be also generated multiple times, hence id is partially generated dynamically.
@Html.DropDownList("TempClsId",new SelectList(Model.ViewOnlyClassRoomList, "Id", "Name"),new { @class = "roomClassStyle", id = String.Format("TempClsId {0}", uniqueId), style = "width: 260px" })

Javascript/Jquery
We need to set the selected value in the dropdownlist once the page load is completed. Hence our code will be set inside document.ready. We are using two loops here, they are not necessary in case we have only one dropdownlist. Here, first we are fetching all the dropdownlist which has TempClsId preceding its name. Once all the dropdownlists are fetched in an array, we look for hidden fields which has name starting with SelectedCls and the ID which is common for both the dropdownlist & the hiddenfield. The selected value is set to the hidden field value at the next step.

<script type="text/javascript">
     $(document).ready(function () {
         var retval = []
         $("select[name^='TempClsId']").each(function () {
             retval.push($(this).attr('id'))
         })
         for (var i = 0; i < retval.length; i++) {            
             var selcls = 'SelectedCls' + retval[i].replace('TempClsId', '');
             var selval = $('input[name^=' + selcls + ']').attr('value');            
             $('#' + retval[i]).val(selval);
         }
     });
    
</script> 

Monday, 30 March 2015

Oracle – Output in XML format and tag customization


DBMS XMLGEN is a PL/SQL package that allows a programmer to extract data in XML format from Oracle database tables.

Select DBMS_XMLGEN.GETXML('Select FIRST_NM FIRSTNAME, MDL_NM MIDDLENAME, LAST_NM LASTNAME, PHON_NR PHONENUMBER FROM SchemaName.EmployeeTable WHERE Emp_ID = 987654321') from dual;

The resultant XML data is below:

<?xml version="1.0" encoding="UTF-8"?>
<ROWSET>
   <ROW>
      <FIRSTNAME>Ho</FIRSTNAME>
      <MIDDLENAME>Chin</MIDDLENAME>
      <LASTNAME>Minh</LASTNAME>     
      <PHONENUMBER>9989798</PHONENUMBER>
   </ROW>
</ROWSET>

We notice that the ‘RowSet’ and ‘Row’ tags are default root and row elements. However we have the option to customize them.

DECLARE
   ctx DBMS_XMLGEN.ctxHandle;
   XML CLOB;
   P_Emp_Id number;
BEGIN
  P_Emp_Id:= 987654321;
   ctx := dbms_xmlgen.newcontext('SELECT FIRST_NM FirstName, MDL_NM MiddleName, LAST_NM LastName, PHON_NR PhoneNumber FROM SchemaName.EmployeeTable  WHERE Emp_ID ='||P_ Emp_Id||'');
   DBMS_XMLGEN.SETROWTAG(CTX, 'ContactPerson');
   dbms_xmlGEN.setRowSetTag(CTX, 'EmployeeApplication');
   XML := DBMS_XMLGEN.GETXML(CTX);
   DBMS_OUTPUT.PUT_LINE(SUBSTR(XML,1,1255));
END;

The output with customized names for RowSet & Row tag: 

<?xml version="1.0" encoding="UTF-8"?>
<EmployeeApplication>
   <ContactPerson>
      <FIRSTNAME>Ho</FIRSTNAME>
      <MIDDLENAME>Chin</MIDDLENAME>
      <LASTNAME>Minh</LASTNAME>      
      <PHONENUMBER>9989798</PHONENUMBER>
   </ContactPerson>
</EmployeeApplication>


We notice that the inner XML tags are caps by default. That can be customized by adding the tag names under double quotes

Select DBMS_XMLGEN.GETXML('Select FIRST_NM “FirstName”, MDL_NM “MiddleName”, LAST_NM “LastName”, PHON_NR “PhoneNumber” FROM SchemaName.EmployeeTable WHERE Emp_ID = 987654321') from dual;

The resultant XML data is below:

<?xml version="1.0" encoding="UTF-8"?>
<ROWSET>
   <ROW>
      <FirstName>Ho</FirstName >
      <MiddleName>Chin</MiddleName >
      <LastName>Minh</LastName >     
      <PhoneNumber>9989798</PhoneNumber >
   </ROW>

</ROWSET>

Monday, 24 November 2014

Reloading a DropDownList using jQuery

Note: This solution will not be applicable for ASP.Net with ViewState (as ViewState will not be updated while using Webmethod call to reload the control).

<asp:DropDownList ID="ddlTemplate" runat="server" ClientIDMode="Static" ></asp:DropDownList>

I kept the control clientIDmode static, it is necessary when we use Master page and the javascript code is in separate file. With HTML combo box control we can remove some of the code specific that is used to handle asp.net control.

The frontend javascript/jquery code :

function GetTemplates() {
    var ddlTestDropDownListXML = '#ddlTemplate';
    var tableName = "TempDataTable";
    $.ajax({
        type: "POST",
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        url: "Search.aspx/GetTemplates",
        data: '{tableName: "' + tableName + '"}',
        success: function (response) {            
            $(ddlTestDropDownListXML).empty().append($("<option></option>").val("[-]").html("Select"));
            $.each(response.d, function () {
                $(ddlTestDropDownListXML).append($("<option></option>").val(this['Value']).html(this['Text']));
            });
        },
        error: function (xhr, status, error) {
            var err = eval("(" + xhr.responseText + ")");
            alert(err.Message);
        }
    });
}


And the code behind looks like below:

        [System.Web.Services.WebMethod]
        public static ArrayList GetTemplates(string tableName)
        {
            AdBusiness ab = new AdBusiness();
            DataTable templateTable = new DataTable();
            ArrayList lstArrTemplate = new ArrayList();            
            try
            {
                templateTable = ab.GetTemplates();
                foreach (DataRow row in templateTable.Rows)
                {
                    lstArrTemplate.Add(new ListItem((string)row[0], (string)row[1]));
                }
                return lstArrTemplate;
            }
            catch (Exception ex)
            {
                return lstArrTemplate;
            }
        }

       

Tuesday, 28 October 2014

Error with Entity Framework 6 after importing Stored Procedures & Functions

I have recently started using Entity Framework 6 for my VS2012 project in 4.5 framework. I was confronted with an error after importing Stored Procedures & Functions, which I did much later after importing the tables.

cannot convert from 'System.Data.Objects.ObjectParameter' to 'System.Data.Entity.Core.Objects.ObjectParameter'

The issue may have arisen because I had used EF5 in my previous project. The solution that I figured out is quite simple. We need to replace

using System.Data.Objects;
 
with
 
using System.Data.Entity.Core.Objects;

Thursday, 23 October 2014

I just added the Ajax control toolkit to my VS2012 project and then run the project. Got the following error.

'MsAjaxBundle' is not a valid script name. The name must end in '.js'

The name it is referring to is available in the Master page, though it doesn’t make clear as to what the error is.
How to solve it? There are a few changes to be made in the Master page.

  1. <asp:ScriptManager runat="server"> must be changed to <ajaxToolkit:ToolkitScriptManager runat="server">
  2.   The Assembly="System.Web" reference must be removed from all the ScriptReferences
  3.   MsAjaxBundle reference must be removed

Once these 3 changes are made, your application will run trouble free.

Tuesday, 14 October 2014

Getting Table Column names in Linq to Entity

We can get the list of column names of a table through SQL query using the following query:

SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS
where TABLE_NAME = 'TableName'

To get the same result while using LINQ to Entity Framework, we need to use Reflection.

using (var context = new DatabaseContext())
    var queryString = typeof(TableName).GetProperties().Select(a => a.Name).ToList();                                     
}

Thursday, 19 June 2014

Records as radio buttons create dynamically

I have a requirement where a set of records has to be displayed as radio button dynamically, the record being fetched from DB.
Let’s start with deciding the ‘rdassets’ as the content holder of the radio buttons.
<div id="rdassets"></div>

We will do an ajax request to the controller with some parameter passed. The result will be checked for null, and then the fetched records will be looped through and appended to the ‘rdassets’. Here below is the ajax call along with the solution to add records as radio buttons in the page.

$("#BtnSearch").click(function () {
            var param = $("#somepagecontrol").val();
            $.ajax({
                url: "/Controller/Method/",
                type: 'POST',
                dataType: 'json',
                data: { Param: param },
                success: function (result) {
                    if (result != null) {
                        $.each(result, function () {
                            $("#rdassets").append(
                                $('<input />', {
                                    type: 'radio',
                                    name: 'rdoAsset',
                                    id: this. RequestId
                                })
                            );
                            $("#rdassets").append(
                                $('<label />', {
                                    'text': this.Item
                                })
                            )
                        });                       
                    }
                    else {

                    }
                },
                error: function (xhr, ajaxOptions, thrownError) {
                    alert('Error in fetching details.');
                }
            });
        });


The ajax response will look similar to the below sample:

[{"RequestId":110,"Item":"Samsung TV"},{"RequestId":103,"Item":"Sample Asset 003"},{"RequestId":206,"Item":"Toyota Cars"}]