Showing posts with label MVC4. Show all posts
Showing posts with label MVC4. Show all posts

Monday, 2 December 2024

How to Create a Generic Method to Get the Enum Description in C#

        public static SelectList GetSelectListForEnumWithDescription(Type enumType)
        {
            var list = new List<Object>();
            Array enumValues = Enum.GetValues(enumType);
         
            foreach (Enum enumValue in enumValues)
            {
                list.Add(new
                              {
                                 ID = (int)Enum.Parse(enumType, enumValue.ToString()),
                                 Value = GetEnumDescription(enumValue)});
                               }
              return new SelectList(list, "ID", "Value");
        }

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

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.


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!

Wednesday, 5 June 2013

Writing multiple condition for a Kendo Grid column Template to fetch the record.

Sometime you are required to write a template for Kendo Grid to fetch the data on a condition below is the column template to write multiple condition to do it. Its easy one, but to remember those small tricky things, I had posted this one.



Column[
{ field: "DateActivated", title: "Activated", width: 50, 
template: '#=(DateActivated==null)?"":(Status=="Requested")?"":
 kendo.toString(kendo.parseDate(DateActivated"),"MM/dd/yyyy")#',filterable: false }]



Happy Coding!

Tuesday, 4 June 2013

Getting the Error "The document has no pages" in PDF reporting Using ItextSharp in Asp.net MVC3/MVC4

Today while working with a project, I got a task to do i.e for creating dynamic PDFs of the View.
So I had started working on that and completed before time.

However , when I tried to put into the azure production environment, i got peculiar error which i had not observed in my dev Environment or in the stage.

The error I got is  "The document has no pages" . I started doing research into it but unable to find any solution. At last, I thought that it might be out of memory or buffering issue, no still that is not the case. the problem arises due to inability to find the relative source path that you had provided to the image source in the view while creating the PDF with the logo or images in it.

So, before deploying to the production server be sure the following things has been checked:

1) The Image file which u have used must be existing in the website inside some folder.
2) Be sure that PDF supports few file formats such as .jpg/.bmp, so use the image of that type.
3) Don't use the image source with relative URL, it will not be able to find the image. It will work in the local but throw an error in production or staging server. So better use the live site followed with the image source.


If you are still getting the same error then just try to render some text and check whether it is rendering or not. If it is rendering then there might be some image rendering issue. Is still getting the error then just recheck your code.


Happy coding!

Friday, 24 May 2013

Jquery Method to Check the File upload control Empty or not, File Size and File Type(e.g. JPG,BMP,PDF)


Html:
<input type="file" id="file" name="file" />
<span id="valFile" class=""></span> // span for showing error message.

CSS:


.field-validation-error {
    color: #f00;
}

.field-validation-valid {
    display: none;
}

.input-validation-error {
    border: 1px solid #f00;
    background-color: #fee;
}


JQuery Snippet:
$(document).ready(function( )
{

//Changing the Error message of the File Upload and checking the File size and File type.
        $("#file").change(function () {

            $("#valFile").html("Please select file."); // Default Error Message
         
            var fileExtension = ['jpeg', 'jpg', 'png', 'gif', 'bmp', 'doc', 'docx', 'pdf'];

            if ($(this).val() != "") { //checking wheather the file uploader is empty or not
             
                //Checking the File type
                if ($.inArray($(this).val().split('.').pop().toLowerCase(), fileExtension) == -1) {
                    $(this).addClass("input-validation-error").removeClass("valid");
                    $("#valFile").addClass("field-validation-error").removeClass("field-validation-valid")
                        .html("Invalid Filetype(only image files/doc/docx/pdf)");
                }
                else {
                    $(this).removeClass("input-validation-error").addClass("valid");
                    $("#valFile").removeClass("field-validation-error").addClass("field-validation-valid");

                    if ((this.files[0].size > 4194304) && ($(this).val() != '')) {
                        $(this).addClass("input-validation-error").removeClass("valid");
                        $("#valFile").addClass("field-validation-error").removeClass("field-validation-valid")
                            .html("File size exceeded 4MB");
                    }
                }
            } else {
                $(this).addClass("input-validation-error").removeClass("valid");
                $("#valFile").addClass("field-validation-error").removeClass("field-validation-valid");
            }
        });

});

Happy Coding!

Wednesday, 22 May 2013

How to create a File Upload with File Validation in Asp.net MVC / How to Use the @Html.TextBoxFor() for File Upload ?

While Wonder how to validate the Upload control in a easy way, I find this solution as the best to do it, although lot of other ways are found.This is because you need not need to write much more code as a normal razor validation will solve the problem.


My View:


 <div id="dvUpload" class="hide fieldControlContainer">
                <div class="innerDivLeft">
                    <label class="blue">Upload Document:</label>
                </div>
                <div class="innerDivRight">
                      @Html.TextBoxFor(model => model.File, new { @class = "inputTextBox", type="file" })
                      @Html.ValidationMessageFor(model => model.File)
                </div>
 </div>

The magic lies with this line  @Html.TextBoxFor(model => model.File, new { @class = "inputTextBox", type="file" }), here it will be rendered as a file upload control rather than a text because we are over riding the default behavior of input tag rendering by specifying it as type="file".

My Controller:



 public ActionResult Index(HttpPostedFileBase file, MyModel model)
        {
                  //Codes written here.
        }


MyModel:

public class MyModel
{

       [Required(ErrorMessage = "Please select file")]     // this is for model validation
        public HttpPostedFileBase File { get; set; }

}

Now your file upload validation will be checked like any other normal control.

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, 16 May 2013

Uploading a file to Server in Asp.net MVC 3 /4.



View page:


@using (Html.BeginForm("Index", "MyController", FormMethod.Post , new { enctype = "multipart/form-data" }))
{
//  Controls for your Model........(see below)

 <div>
                <div class="innerLeftContainer">
                    <label >Full Name:</label>
                </div>
                <div class="innerRightContainer">
                    @Html.TextBoxFor(model => model.FullName, new {@class = "inputTextBox"})
                    @Html.ValidationMessageFor(model=>model.FullName)
                </div>
            </div>


<div id="dvUpload">
                <div class="innerLeftContainer">
                    <label>Upload Document:</label>
                </div>
                    <div class="innerRightContainer">
                        <input type="file" id="DocumentUpload" name="file" />
                    </div>
            </div>


}


Note: The Form Method and the enctype is highly required for uploading your file to the server orthrwise you will always get the HttpPostedFileBase as null.


Action Method: ( in the Controller)
 [HttpPost]
        public ActionResult Index(HttpPostedFileBase file, MyModel model)
        {
            // Verify that the user selected a file
            if (file != null && file.ContentLength > 0)
            {
                // extract only the fielname
                var fileName = Path.GetFileName(file.FileName);
                if (fileName != null)
                {
                    // store the file inside ~/App_Data/uploads folder
                    var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
                    file.SaveAs(path);
                }
            }
            // redirect back to the index action to show the form once again
            return RedirectToAction("Index");
        }

Wednesday, 24 April 2013

Searching Records from the Kendo Grid by Date given in the Search Box.

While working on a project I came to an issue in kendo grid i.e to search the Grid records using Date.
Say , I had an accounts list from a bank in which lots of data are displayed including A/C opening date, Last log-in, Last transaction, Last Unsuccessful Log-in and there is a search box that finds the records when the date is given in the search box. But to my dismay it doesn't works for me, after spending a valuable of 1 day of my work , I had got the success.

So here is the image below:





The Code to make your grid work for dates filtration or searching:

In the web page(.html / .cshtml / .jsp etc)
<div id="grid"></div>

Script:
<script type="text/javascript">


$(document).ready(function () {
       initGrid();
      
/// This function is called when you start typing in the search textbox. Here Id of search textbox is #search.
    $('#search').keyup(function () {
        clearTimeout($.data(this, 'timer'));
        var wait = setTimeout(searchDataSource, 500);
        $(this).data('timer', wait);
    });

});



 function searchDataSource() {
        var query = $("#search").val();
        var $filter = [
                       { field: "AccOpenDate", operator: "eq", value: new Date(query) },
                       { field: "LastLogin", operator: "eq", value: new Date(query) },
                       { field: "LastTrans", operator: "eq", value: new Date(query) },
                       { field: "FaliureLogin", operator: "eq", value: new Date(query) }
        ];

        if (query.length > 2)  // search only when the no. of character typed is greater than 2
        {
            grid.data("kendoGrid").dataSource.filter({
                logic: "or",
                filters: $filter
            });

        } else if (query.length == 0)
            grid.data("kendoGrid").dataSource.filter([]);
    }


 function initGrid() {
        grid = $("#grid").kendoGrid({
            dataSource: {
                transport: { read: "/Bank/accounts" },
                schema: { data: "Data", total: "Total" },
                pageSize: 30,
                serverPaging: false,
                serverFiltering: false,
                serverSorting: false
            },
            height: gridHeight,
            change: function () {
                var selectedRows = this.select();
                selectedElement = this.dataItem(selectedRows[0]);
                showActionPane(selectedElement.Name != null && selectedElement.Name != "");
            },
            selectable: "single",
            filterable: true,
            sortable: true,
            pageable: true,
            resizable: true,
            columns: [

                { field: "Name", title: "Name", width: 60, template: '<a href="/Account/Details/#=Id#">#=Name#</a>' },
                { field: "Status", title: "Status", width: 50 },
                { field: "AccountType", title: "Account Type", width: 80 },
                { field: "AccOpenDate", title: "A/c Open Date", width: 50, template: '#=(AccOpenDate==null)?"":kendo.toString(kendo.parseDate(AccOpenDate,"0:MM/dd/yyyy"),"MM/dd/yyyy") #', filterable: true, format: "{0:M/d/yyyy}", type: "date" },
                { field: "LastLogin", title: "Last Login", width: 50, template: '#=(LastLogin==null)?"":kendo.toString(kendo.parseDate(LastLogin,"0:MM/dd/yyyy"),"MM/dd/yyyy") #', filterable: false, format: "{0:M/d/yyyy}", type: "date" },
                { field: "LastTrans", title: "Last Transaction", width: 50, template: '#=(LastTrans==null)?"":kendo.toString(kendo.parseDate(LastTrans,"0:MM/dd/yyyy"),"MM/dd/yyyy") #', filterable: false, format: "{0:M/d/yyyy}", type: "date" },
                { field: "FaliureLogin", title: "Unsuccessful Login", width: 50, template: '#=(FaliureLogin==null)?"":kendo.toString(kendo.parseDate(FaliureLogin,"0:MM/dd/yyyy"),"MM/dd/yyyy") #', filterable: false, format: "{0:M/d/yyyy}", type: "date" }
            ]
        });
    }

output:
Search records by Date through Search Textbox text:  ( here searching the record occurs on all the columns)



Search records by Date through filter Button: ( here searching the record which has opened on 04/04/2013. So two records where as in the above it is searching all the columns having 04/04/2013. so three records. 


Tuesday, 23 April 2013

How to check all the check box when All check-box is checked and uncheck All check-box, if one of the check-box from the group is unchecked


       
<form name="frmChkForm" id="frmChkForm">
<input type="checkbox" name="chkcc9" id="chkAll">Check Me
<input type="checkbox" name="Bowler" class="chkGroup">Bowler
<input type="checkbox" name="Batsman" class="chkGroup">Batsman
<input type="checkbox" name="AllRounder" class="chkGroup">AllRounder
</form>

$("#chkAll").click(function() {
   $(".chkGroup").attr("checked", this.checked);
});

With added functionality to ensure the check all checkbox gets checked/dechecked if all individual checkboxes are checked:

$(".chkGroup").click(function() {
  $("#chkAll")[0].checked = $(".chkGroup:checked").length == $(".chkGroup").length;
});


Happy Coding!

Blank out a form/ reset a form with jQuery


First method:
<form id="form">
<input type="text" value="Here is some data" id="data" />
<input type="button" value="Clear Input" id="button" />
</form>

$(function(){
 
    $('#button').click(function(){
       $(':input','#form').not(':button, :submit, :reset, :hidden').val('').removeAttr('checked,selected');
    });
});

Second method:
function clearForms()
{
  var i;
  for (i = 0; (i < document.forms.length); i++) {
    document.forms[i].reset();
  }
}

Happy Coding!

Monday, 22 April 2013

Ajax method of calling Action method of a controller:

I need to call a action method in order to save the uploaded image file using Jquery or the Ajax method. So below is the code for it.


$.ajax({
           url:
"/Image/UploadTest", // Image is the controller & UploadTest is Action Method

           type: "POST",
           data: $("#frmTest"
).serialize(),   // Here provide the form Id
           async:
false,
           cache:
false,                      // Don't keep the cache
           beforeSend:
function () {  // This Executes before calling the Ajax Request
                  $(
"#uploadProgress").show();   // Here I am showing Uploader image
              },
           complete:
function () {
                  $(
"#uploadProgress").html("Upload completed"); 

                // Executes on Ajax request complete
              },
          success:
function (msg) {

                 
if (msg == "ok")
                      $(
"#uploadProgress").hide();  // hiding the uploader image on successs
                 
else
                      alert(
"Error while uploading");

              }
          });

Reading a CSV file with Linq


A simple single line of code  to read the CSV file in Linq:

rawFile = (from line in File.ReadAllLines(fileName).AsParallel()
            select line.Split(',')).ToList();

Happy Coding!

Wednesday, 6 March 2013

Getting the Error: "Templates Can be used only with field access,property access, single dimension, or Single-parameter Custom Indexer Expression" in Asp.Net MVC3/MVC4



While working on an MVC3 project I need to Show the short date  & time in the display for HTML helper, but when I used it is throwing the above error, the reason behind it was that the HTML helper DisplayFor and EditorFor  takes directly the properties of the model rather than the functions which are associated with it.
  @Html.DisplayFor(model => model.DateStart.Value.ToShortDateString( ))

To fix the above situation you can simply remove the DisplayFor and use as :

@if(Model.DateStart!=null)
{
  Model.DateStart.ToShortDate( )
}


However, the best method to fix this situation is create a partial class with the above field and use the DisplayFormat properties to it with the one you wants.

    [DisplayName("Start Date")]
    [DisplayFormat(DataFormatString="{0:MM/dd/yyyy}",  ApplyFormatInEditMode=true)]
    public System.Nullable<System.DateTime> ModifiedStartDate
    {
        get
        {
            return this.StartDate.ToShortDateString( );
        }
        set
        {
            this.StartDate = value;
        }
    }


How to use it:
  @Html.DisplayFor(model => model.ModifiedStartDate)