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 control.

The frontend javascript/jquery code :

function GetTemplates() {
    var ddlTestDropDownListXML = '#ddlTemplate';
    var tableName = "TempDataTable";
        type: "POST",
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        url: "Search.aspx/GetTemplates",
        data: '{tableName: "' + tableName + '"}',
        success: function (response) {            
            $.each(response.d, function () {
        error: function (xhr, status, error) {
            var err = eval("(" + xhr.responseText + ")");

And the code behind looks like below:

        public static ArrayList GetTemplates(string tableName)
            AdBusiness ab = new AdBusiness();
            DataTable templateTable = new DataTable();
            ArrayList lstArrTemplate = new ArrayList();            
                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;
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:

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();
                url: "/Controller/Method/",
                type: 'POST',
                dataType: 'json',
                data: { Param: param },
                success: function (result) {
                    if (result != null) {
                        $.each(result, function () {
                                $('<input />', {
                                    type: 'radio',
                                    name: 'rdoAsset',
                                    id: this. RequestId
                                $('<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"}]

Parameter passing at Url.Action

What is my goal: Open a model window (partial page) through a javascript function, passing a parameter with it.
Where the challenge is: The parameter cannot be directly added in the url Action.
What is the solution: Add a hardcoded parameter value and replace it in the next step
Normally we would like to pass the parameter in the url in the below way:
reqid = paramvalue;
url = '@Url.Action("PageName", new { requestId = reqid })';

This above code doesn’t work. Below is the sample code which works perfectly. We set a dummy value “-1” as the parameter in the first step. In the next step we replace the dummy value with the actual one.

<div id="modelwindow">

function ViewRecord(objValue) {       
        reqid = objValue;
        url = '@Url.Action("PageName", new { requestId = "-1" })';
        url = url.replace("-1", reqid);
        modelwindow = $("#modelwindow")
                title: true,
                modal: true,
                visible: false,
                resizable: true,
                width: '800px',
                content: url

            modelwindow.title("Request Details");


Wednesday, 19 March 2014

Sending email through MS Sql Server

This sample is intended for MVC, C# code. The front end code consists of Kendo UI & jquery.
I will be using asynchronous mode to upload the file to a temporary destination path “FileUploads” in the server. Users need to be given access to this folder first.

public ActionResult SaveAttachment(HttpPostedFileBase ImageFile)
       imagepath = ImageFile.FileName;
       var destinationPath = Path.Combine(Server.MapPath("~/FileUploads"), imagepath);
       FileInfo files = new FileInfo(destinationPath);
       imagepath = destinationPath;

Once the file has been uploaded to the folder in server, our program needs a method to get the server IP. (We may hardcode the IP for server, but that will not be ideal.)

        private string GetIP()
            IPHostEntry host;
            string localIP = "?";
            host = Dns.GetHostEntry(Dns.GetHostName());
            foreach (IPAddress ip in host.AddressList)
                if (ip.AddressFamily == AddressFamily.InterNetwork)
                    localIP = ip.ToString();
            return localIP;

public ActionResult EMail([DataSourceRequest] DataSourceRequest request, Somemodel model)
string ip = GetIP();
       string fileUploadPath = @"\\" + ip + "\\FileUploads\\";
String[] filecount = FileNames.Split(','); //Here get FileNames from FileUploads folder
//Handling multiple files in the attachment here, attachments must be separated by ;
       foreach (string filename in filecount)
                     if (attachmentPath == "")
                           attachmentPath = fileUploadPath + filename;
                     attachmentPath = attachmentPath + ";" + fileUploadPath + filename;
//Use some business entity to send the mail information to Data access layer
       SomeBusinessEntity mailMaster = new MailMaster
                     Recipients = model.Recipients,
Subject = model.Subject,
                     Body = System.Web.HttpUtility.HtmlDecode(model.Body),
                     BodyFormat = model.BodyFormat,                       
                     FileAttachments = attachmentPath
                     CreatedDate = DateTime.Now

You may directly call the msdb.dbo.sp_send_dbmail stored procedure from DAL, or the other option is to write a separate stored procedure which will then call the system defined one.
If all code goes fine, your mail will be reaching the intended recipient.
This example also solves the issue "attachment file is invalid" – error 22051 as we use GetIP() to get IP of the server.

Tuesday, 11 March 2014

Kendo UI Tips

How to clear Kendo fields from javascript function:

    function ClearFields() {
        $("# Subject ").val(''); //Kendo TextBox control
        $("#Importance").data("kendoDropDownList").value('-1'); //Kendo DropDownList control
        var editor = $("#Body").data("kendoEditor"); //Kendo Editor

How to set Kendo Dropdownlist values/text if we aren’t fetching from DB.
How to add the default (optional) field.

                  @(Html.Kendo().DropDownListFor(model => model.Importance)
                        .OptionLabel("-- Select --")
                        .BindTo(new List<SelectListItem>() {                               
                            new SelectListItem() {
                                Text = "NORMAL",
                                Value = "0"
                            new SelectListItem() {
                                Text = "PERSONAL",
                                Value = "1"


Will keep on adding to it with time...

Wednesday, 26 February 2014

Javascript function: Sending MVC Razor parameter containing special characters

I am working on MVC Razor. I have to call a javascript function loadHierarchyData  on click event. It works fine if we use the Razor format @item.HierarchyName which allows the parameters to be passed to the function successfully.
<div class="tile" onclick="javascript:loadHierarchyData('@item.HierarchyName',@item. HierarchyDetailId,'@item.HierarchyCode')" >

However we face issue when the dynamic parameter contains special characters. In this example our parameter contains ‘ character. The solution is to include \\ character in front of the special character as shown in the below example.
<div class="tile" onclick="javascript:loadHierarchyData('@item.HierarchyName.Replace("'","\\'")',@item. HierarchyDetailId,'@item.HierarchyCode')" >