Showing posts with label Razor. Show all posts
Showing posts with label Razor. Show all posts

Tuesday, 18 February 2014

How to open a new tab On click of a hyper-linked column in Telerik Razor Grid

Today i got a requirement to open a external URL in a tab when the linked column is clicked.
This  can be achieved by simply adding the client template/ template to the linked column.

1) Using Template Attribute in the Telerik Grid
column.Bound(a => a.Website)
      .Template(@<text><a href="@Url.Content(item.Website)" target="_blank">@item.Website</a></text>)
      .HeaderTemplate(
        @<text>
    <a href="javascript:void(0)" class="t-link" orderby="Website">Website</a>
@Html.TextBoxFor(m => m.Filter.Website)         
</text>);

2) Using Client Template Attribute in the Telerik Grid


column.Bound(a => a.Website)
    .ClientTemplate("<a href='<#= Website #>' target='_blank'><#= Website #></a>")
    .HeaderTemplate(
        @<text>
    <a href="javascript:void(0)" class="t-link" orderby="Website">Website</a>
@Html.TextBoxFor(m => m.Filter.Website)         
</text>);

Output:


But the really annoying is that when you click the link it is throwing error  as
 "The resource you are looking for has been removed, had its name changed, or is temporarily unavailable"



This is because the IIS is unable to resolve the path.

Solution to the above issue:

The above issue can be fixed by a simple trick, just you need to append the http:// to the website in the client template or in the template attribute. See the code below:

column.Bound(a => a.Website)
      .Template(@<text><a href="@Url.Content("http://"+item.Website)" target="_blank">@item.Website</a></text>)
      .HeaderTemplate(
        @<text>
    <a href="javascript:void(0)" class="t-link" orderby="Website">Website</a>
@Html.TextBoxFor(m => m.Filter.Website)         
</text>);

Note: Similarly if it is a mail ID column then, use mailto: as the prefix.

Thats it, Enjoy!

Monday, 15 July 2013

Compile Time View Checking In Asp.net MVC

You might have noticed that in MVC3/MVC4 if you had done some thing wrong in the view files it will not throw any error during compilation and it will build successfully. The error in the file is only noticed during executing/rendering the view file. So in order to trap the error during the compilation time you can follow the method below:

Step-1 :
Open your solution project file in any XML Editor or in the Visual Studio itself  and you will find a tag named
<MVCBuildViews>, here it false and just make it true and save it.

<MVCBuildViews>false</MVCBuildViews>  
 change it to 
<MVCBuildViews>true</MVCBuildViews>


Thats all, so now when your view has any error then it will throw error during the compilation.


The Use of ALL Operator in LINQ

Today, I came across the All operator in LINQ. This operator returns bool value rather than records after condition is satisfied. The operator will be highly helpful when you need some kind of validation to find unique data. for e.g. Checking the existing email  or UserID registered and so on.


Lets Go with a Example to do the Task:

int [] array = { 1,2,3,4,5 };

bool result = array.All(value => value > 2 );

Console.WriteLine(result);  // Here it will print False since it will check all the values and                                         // all the values must be grater than 2.


 result = array.All(value => value < 6 );
Console.WriteLine(result); // Here it will print True since it will check all the values and                                          // found all values are less than 6.


Hope it helps you!

Monday, 17 June 2013

Error 349: Duplicate headers received from server in Google Chrome while rendering PDF using ITextSharp in Asp.Net MVC



While working on generating  PDF in Asp.Net MVC3, I got a peculiar error while rendering the PDF in Chrome browsers, which is not being found in any other browsers like Internet Explorer or Fire Fox.
This error comes because chrome browsers doesn't ignore duplicate headers. This can be addressed easily the following ways, if you or your web app is sending out headers. Then check the following things:

 1. Enclose fileName using “”. i.e
Response.Addheader('Content-Disposition: attachment; filename="' + fileName '"');
instead of
Response.Addheader('Content-Disposition: attachment; filename='+ fileName);
2. If possible replace spaces and commas (,) with underscores (_)
 string regExp = @"[^\w\d]";
Response.AddHeader("content-disposition""attachment;filename=" + "Test_PDF_" + 
                           Regex.Replace(model.CompanyName, regExp, "_")+ "_" +
                              Regex.Replace(model.FullName, regExp, "_") + "_" +                                                         DateTime.Now.ToShortDateString());teString());

3. Explicitly tell Asp.Net MVC to override headers by setting optional replace parameter to true.
Response.AddHeader("Content-type: application/pdf",true);
Happy Coding!

Friday, 14 June 2013

How to prevent the multiple submit of record in ASP.Net MVC using JQuery

There are various methods are available to do that one, it can be done using JQuery, using sessions or Filters.


Method -1 ( Using JQuery Approach)
 $('form').submit(function () {
        if ($(this).find('.input-validation-error').length == 0) {
            $(this).find(':submit').attr('disabled''disabled');
        }
    });

This is the simplest method to prevent the multiple submission of the record in MVC and even it works on JQuery Unobstructive validations.

Happy Coding!

Friday, 17 May 2013

How to make a textbox to accept only integers as Input.

Html Page:
 <input type="text" name="age" id="txtAge" />&nbsp;<span id="errormsg"></span>

JQuery Snippet for the above TextBox:

Method-1:
$(document).ready(function () {
  //called when key is pressed in textbox
  $("#txtAge").keypress(function (e) {
     //if the letter is not digit then display error and don't type anything
     if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
        //display error message
        $("#errormsg").html("Digits Only").show().fadeOut("slow");
               return false;
    }
   });
});

Method-2:
$(document).ready(function () {
    $("#txtAge").keydown(function (e) {
        if (e.shiftKey) e.preventDefault();
        else {
            var nKeyCode = e.keyCode;
            //Ignore Backspace (Keycode=8), Tab keys(Keycode=9)  & Delete(Keycode=46)
         if (nKeyCode == 8 || nKeyCode == 9 || nKeyCode == 46) return;
            if (nKeyCode < 95) {
                if (nKeyCode < 48 || nKeyCode > 57) e.preventDefault();
            } else {
                if (nKeyCode < 96 || nKeyCode > 105) e.preventDefault();
            }
        }
    });
});

Enjoy!

Thursday, 31 January 2013

A simplest way of Encrypting and Decrypting in C#.

Microsoft has provided a simplest way of encoding and decoding of strings  by using the System.Text.Here is the Code below to do Encryption and Decryption.


using System.Text;
For Encryption
 string encryptedString= Convert.ToBase64String(Encoding.Unicode.GetBytes("Text to Encrypt"));

For Decryption
 string decryptedString=Encoding.Unicode.GetString(Convert.FromBase64String("Text to Decrypt"));


How simple is it?

Note:This type of Encryption is not good for encrypting the passwords or credit card or Debit card information's or Online transactions as these are prone to decoding easily and can be hacked. so these are good for sending email in coding format through URL etc.

Dynamically adding Controls in the Asp.Net MVC3 / MVC4.

This post is so simple that you can easily understand how to add controls to your view dynamically and delete controls dynamically, i.e. here the controls are created dynamically and are deleted dynamically.

The Above thing can be achieved  in 3 steps:

1. Creating the View.
2. Handling the Click event and creating/deleting the Dynamic Control.
3. Pulling the data from the View to the Controller.


1.Creating the View:

First of all you need to create a view for the Dynamic control Adding.

For Example:
<div>
    <label class="smallFontForAppSelector">Name</label>
    &nbsp;&nbsp;
    <label class="smallFontForAppSelector">
        Degree of Similarity
    </label>
    <label class="smallFontForAppSelector">
        URL/Location
    </label>
    <label class="smallFontForAppSelector">
        Info
    </label>
    <label class="smallFontForAppSelector">
        GUID
    </label>
</div>
<div id='AppSelectorGroup'>
    <div id="AppSelectorBox_1" style="display: block; float: left;">
        <div class="editor-label">@Html.Label("Best Alternative App:")</div>
        <div class="editor-field">
            @Html.TextBox("Name", null, new { id = "textboxName1" })
            &nbsp;&nbsp;
            @Html.DropDownList("Degree", Util.GetSelectListForDegreeOfSimilarity(typeof(DegreeOfSimilarity)),"--Select--", new { id = "ddlDegree1" })
            &nbsp;&nbsp;
             @Html.TextBox("Location", null, new { id = "textboxLocation1" })
            &nbsp;&nbsp;
             @Html.TextBox("Info", null, new { id = "textboxInfo1" })
            &nbsp;&nbsp;
             @Html.TextBox("GUID", null, new { id = "textboxGUID1", @class="deleteAppselector" })
        </div>
    </div>

    <a href="#Add" class="addURL addURLBlack" id="addAppSelector">+</a> <a href="#Delete" class="addURL addURLRed" id="removeAppSelector">-</a>
    <div class="clear-fix"></div>
</div>

Css:

#AppSelectorGroup input {
    width: 140px!important;
}

.smallFontForAppSelector {
    display: block;
    float: left;
    font-size: 12px;
    position: relative;
    text-align: center;
    top: 10px;
    width: 165px;
}

.divinline {
    display: inline;
    float: left;
    width: 1100px;
}



.addURL {
    background-color: #FFF;
    border: 1px solid Gray;
    font-weight: bold;
    cursor: pointer;
    display: block;
    font-size: 15px;
    height: 23px;
    margin-left: 13px;
    margin-top: 10px;
    text-align: center;
    width: 25px;
    float: left;
}

.addURLRed {
    color: red!important;
}

.addURLBlack {
    color: #000 !important;
}

In the Enum Class:
public enum DegreeOfSimilarity
    {
        [Description("Identical")]
        Identical,
        [Description("Knock off")]
        Knockoff,
        [Description("3rd party client")]
        ThirdPartyClient,
        [Description("Functionality similar")]
        FunctionalitySimilar,
        [Description("Competitor's app")]
        CompetitorsApp,
        [Description("Mobile site substitute")]
        Substitute
    }

MY Util Class:

  public static SelectList GetSelectListForDegreeOfSimilarity(Type enumType)
        {
            List<AppDegreeOfSimilarity> appDegreeOfSimilarity = new List<AppDegreeOfSimilarity>();
            var categories = new List<string>(Enum.GetNames(enumType));

            foreach (var item in categories)
            {
                string description = ModelUtil.GetEnumDescription((DegreeOfSimilarity)Enum.Parse(typeof(DegreeOfSimilarity), item));
                appDegreeOfSimilarity.Add(new AppDegreeOfSimilarity() { Name = description, Value = item });     //LocalizationResourceProvider.GetLocalizedString("lbl" + item));
            }
            return new SelectList(appDegreeOfSimilarity, "Value", "Name");
        }


Get the Enum Description:

  public static string GetEnumDescription(Enum value)
        {
            FieldInfo fi = value.GetType().GetField(value.ToString());

            DescriptionAttribute[] attributes =
                (DescriptionAttribute[])fi.GetCustomAttributes(
                typeof(DescriptionAttribute),
                false);

            if (attributes != null &&
                attributes.Length > 0)
                return attributes[0].Description;
            else
                return value.ToString();
        }
Jquery for handling the Click Event and Creating the Dynamic Controls:
   //----------Begin: For Creating App Selector Groups---------------//
        var deleteAppSelectror = $(".deleteAppselector").length;




/* For Adding the Control */
 $("#addAppSelector").click(function () {
     if (deleteAppSelectror == 10) {
                $("#addAppSelector").hide();
                $("#removeAppSelector").show();
                //alert("Only 10 URLs are allowed");
                return false;
            }
            else {
                $("#addAppSelector").show();
                $("#removeAppSelector").show();
            }
     deleteAppSelectror++;
     var newTextBoxDiv = $(document.createElement('div'))
         .attr("id", 'AppSelectorBox__' + deleteAppSelectror);
              

            newTextBoxDiv.append('<div class="editor-label"><label>Best Alternative App: </label></div>' +
                '<div class="editor-field"><input type="text" name="Name" id="textboxName' + deleteAppSelectror + '" value="" />' + '&nbsp;&nbsp;&nbsp; <select name="Degree" id="ddlDegree' + deleteAppSelectror + '" class="valid"><option value="Identical">Identical</option> <option value="Knockoff">Knock off</option> <option value="ThirdPartyClient">3rd party client</option> <option value="FunctionalitySimilar">Functionality similar</option> <option value="CompetitorsApp">Competitors app</option> <option value="Substitute">Mobile site substitute</option> </select>' +
                '&nbsp;&nbsp;<input type="text" name="Location" id="textboxLocation' + deleteAppSelectror + '" style="margin-left:8px;" value="" />' +
              '&nbsp;&nbsp;<input type="text" name="Info" id="textboxGUID' + deleteAppSelectror + '" style="margin-left:8px;" value="" />' +
                  '&nbsp;&nbsp;<input type="text" name="GUID" class="deleteAppselector" id="textboxInfo' + deleteAppSelectror + '" style="margin-left:8px;" value="" />' +
                '</div><div class="clear-fix"></div>');

            newTextBoxDiv.appendTo("#AppSelectorGroup");


            if (deleteAppSelectror == 10) {
                 $("#addAppSelector").hide();
                 $("#removeAppSelector").show();

                 return false;
             }
             return true;
         });

/* For Removing the Control */   
     $("#removeAppSelector").click(function () {
            if (deleteAppSelectror == 1) {
                $("#removeAppSelector").hide();
                $("#addAppSelector").show();
                return false;
            }
            else {
                $("#removeAppSelector").show();
                $("#addAppSelector").show();
            }

            $('.deleteAppselector').last().parent().parent().remove();
            deleteAppSelectror--;
            if (deleteAppSelectror == 1) {
                $("#removeAppSelector").hide();
                $("#addAppSelector").show();
                return false;
            }
            return true;
        });

        //----------End: For Creating App Selector Groups---------------//



Controller: Action Method to Get the Data from View and to do processing
         [HttpPost]
        public ActionResult CreateAppSelector(AppSelectorRecordViewModel model, List<string> name, List<string> degree, List<string> location, List<string> info,List<string> guid)
        {
            GetAllBestAltApp(model, name, degree, location, info, guid);
            return CreateAppSelector(model);
        }


 private void GetAllBestAltApp(AppSelectorRecordViewModel model, List<string> name, List<string> degree, List<string> location, List<string> info, List<string> guid)
        {
            int count = 0;
            List<BestAlternatives> bestAltApps = new List<BestAlternatives>();
            if (name != null)
            {
                foreach (var n in name)
                {
                    if (n != string.Empty)
                    {
                        BestAlternatives bestAltApp = new BestAlternatives { Name = name[count], DegreeOfSimilarity = degree[count], Location = location[count], Info = info[count], GUID = guid[count] };
                        count++;
                        bestAltApps.Add(bestAltApp);
                    }
                }

                if (bestAltApps.Any())
                {

                    model.AppSelector.BestAlternatives = ModelUtil.SerializeObject(bestAltApps);
                }
                else
                {
                    model.AppSelector.BestAlternatives = null;
                }
            }
            else
                model.AppSelector.BestAlternatives = null;
        }


Result: