Showing posts with label jquery. Show all posts
Showing posts with label jquery. Show all posts

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> 

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"}]

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.

[HttpPost]
public ActionResult SaveAttachment(HttpPostedFileBase ImageFile)
{
       imagepath = ImageFile.FileName;
       var destinationPath = Path.Combine(Server.MapPath("~/FileUploads"), imagepath);
       FileInfo files = new FileInfo(destinationPath);
       ImageFile.SaveAs(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;
              }
              else
              {
                     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
       };
       MailDAL.Email(mailMaster);
}

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.