Announcement

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

Server side ajax paging using jquery MVC4

Server Side AJAX paging using jquery in MVC4


Every developer has to code for a view that displays all the records. But what if the database consists of thousands of records? In that case displaying all the records on the view is not good. Rather some sort of paging must be provided that will give the user the ability to navigate among the records and even provide the developer to have fast web page. So, we need to fetch the records on demand and display them on the view. This will be much fast if records are fetched using AJAX. Pagenation can be done in different ways. One way is to use Html Helpers. i.e., @Html.PagedList. The other way is using AJAX. So, how AJAX is used for fast paging?

Store Password in Encrypted form

Store Password in Encrypted Form

Now a days security is a big issue for any organisation or an individual. Whether you do surfing on internet or use your ATM. Everywhere we can find in some or the other way to secure our data or transaction or just to be on the safe side.

Software Engineers or Developers try hard to provide security for the applications they built. One common way to provide security is to provide Login credentials for their applications. To improve it further, 3-attempts login feature is provided. After 3 unsuccessful attempt, the applications gets blocked.

There are lot of other ways to provide security.

Now, what is more important is to secure your data. i.e., What if somebody peeps into your database? The person will get to know users credentials of your system or application.

One way to prevent this is to store password in encrypted form.

So let us learn how to store password in encrypted form using a reliable MD5 algorithm.

Writing an Image in Excel File



Writing an Image in Excel File

This post will explain you how to write an image in excel file. You first need to define the path of the image in web.config file. Just write the code in web.config file as
<add key="LogoPath" value="E:\\MyProject.Web\\Content\\Images\\ProjectLogo.jpg"/>

Now draw this logo into your excel file using System.Drawing.Image class. An abstract base class that provides functionality for the Bitmap and Metafile descended classes. We will use FromFile() method that is used to create image from the specified file. The file path is passed as an argument to FromFile() method. We can use its overloaded form where we need to specify another argument as boolean i.e., true or false. This specifies whether to use embedded color management information in that file.

Once this Image is created, now create final imagepath that will be rendered in the excel. Here we need to create an image tag(<IMG="" SRC="" WIDTH="" HEIGHT="" />). In this we need to specify the image's width and height by using the above created Image.

Now our iamgepath is ready for finally rendering it into excel file. The code is as follows:

NOTE: This code has a limitation. You need to specify the path every time whenever the image location is changed. The better solution is to use a mapping between ServerPath and LocalPhysicalPath.

HttpContext.Response.Write("<TR style='font-size:12.0pt; text-align:center; font-style:italic; text-decoration:underline; font-weight:bold; font-family:Book Antiqua;'>");
string filePath = System.Configuration.ConfigurationManager.AppSettings["LogoPath"];
System.Drawing.Image imgPhoto = System.Drawing.Image.FromFile(filePath);
string imagepath = string.Format("<img src='{0}' width='{1}' height='{2}'/>", filePath, imgPhoto.Width, imgPhoto.Height);
imgPhoto.Dispose();
HttpContext.Response.Write("<Td>");
HttpContext.Response.Write(imagepath);
HttpContext.Response.Write("</Td>");
HttpContext.Response.Write("</TR>");

Pagination in MVC4



Pagination in MVC4

This post will explain pagination in MVC4.

You need to install NuGet Package manager named PagedList. You can get the same by clicking NuGet PagedList.
Once this is installed in your project, add a reference to PagedList and PagedList.Mvc dlls. In your view, include the following code at the top as:

@using PagedList;
@using PagedList.Mvc;


The model which your view will be returning should be IPagedList<> rather than IEnumerable<>.

Now you are ready to use the Html Helper for the PagedList. i.e., @Html.PagedListPager() where you can also specify various display options for the pagination.

The view will look like this:

@using PagedList;
@using PagedList.Mvc;
@model IPagedList&ltDistribution.Entities.District&gt
@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<link href="../../Content/PagedList.css" rel="stylesheet" type="text/css" />
<h2>Display</h2>
@Html.ActionLink("Create New", "Create")


The various display options for the PagedList can be found in PagedList.Mvc namespace 
inside the class PagedListRenderOptions.

You can make any changes as per the requirement.


public PagedListRenderOptions()
{
 DisplayLinkToFirstPage = PagedListDisplayMode.IfNeeded;
 DisplayLinkToLastPage = PagedListDisplayMode.IfNeeded;
 DisplayLinkToPreviousPage = PagedListDisplayMode.IfNeeded;
 DisplayLinkToNextPage = PagedListDisplayMode.IfNeeded;
 DisplayLinkToIndividualPages = true;
 DisplayPageCountAndCurrentLocation = false;
 MaximumPageNumbersToDisplay = 10;
 DisplayEllipsesWhenNotShowingAllPageNumbers = true;
 EllipsesFormat = "…";
 LinkToFirstPageFormat = "««";
 LinkToPreviousPageFormat = "«";
 LinkToIndividualPageFormat = "{0}";
 LinkToNextPageFormat = "»";
 LinkToLastPageFormat = "»»";
 PageCountAndCurrentLocationFormat = "Page {0} of {1}.";
 ItemSliceAndTotalFormat = 
"Showing items {0} through {1} of {2}.";
 FunctionToDisplayEachPageNumber = null;
 ClassToApplyToFirstListItemInPager = null;
 ClassToApplyToLastListItemInPager = null;
 ContainerDivClasses = new [] { "pagination-container" };
 UlElementClasses = new[] { "pagination" };
 LiElementClasses = Enumerable.Empty();
}

The Complete View is as:

View


@using PagedList;
@using PagedList.Mvc;
@model IPagedList<distribution .entities.district="">
@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<link href="../../Content/PagedList.css" rel="stylesheet" 
type="text/css" />
<h2>Display</h2>
<p>
    @Html.ActionLink("Create New", "Create")
</p>
<table>
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.First()
.State.StateName)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.First()
.DistrictName)
        </th>
        <th></th>
    </tr>
@foreach (var item in Model) {
    <tr>
        <td>
         @Html.DisplayFor(modelItem => item.State.StateName)
        </td>
        <td>
         @Html.DisplayFor(modelItem => item.DistrictName)
        </td>
        <td>
         @Html.ActionLink("Edit", "Edit", new 
{ id=item.DistrictId }) |
         @Html.ActionLink("Details", "Details", new 
{ id=item.DistrictId }) |
         @Html.ActionLink("Delete", "Delete", 
new { id=item.DistrictId })
        </td>
    </tr>
}
</table>
@Html.PagedListPager(Model,page=>
Url.Action("Index",new {page}), 
new PagedListRenderOptions 
{Display=PagedListDisplayMode.IfNeeded, 
DisplayPageCountAndCurrentLocation=true})


Now that your view is ready, you will have to write code for your controller for the pagination. This is as under:

Controller

public ActionResult Index(int? page)
{
return View(db.Districts.ToList()
.ToPagedList(page ?? 1,4));
}



Validations in MVC 4


There are two ways to add custom validations in MVC 4:
  1. Using Data Annotations with Model Binder.
  2. Using Data Annotations in Entity Framework.
Let us see:
  1. Using Data Annotations with Model Binder
Inorder to use DataAnnotation with Model Binder, you need to add references to the following dlls:


How to include favicon in your website in MVC?

Inorder to include favorite icon in your website you just have to provide a reference in the link tag to the favorite icon (provided you have a favorite icon).

It is also known as Shortcut icon, Tab icon, Website icon or Bookmark icon.

<link href="~/favicon.ico" rel="shortcut icon" type="image/x-icon" />

If you do not have a favorite icon than you can create your own favorite icon by importing the image. Just visit favicon generator.

How to create a connection string from Web.config file using stored procedure?

ConnectionStringInWeb.ConfigFile techiners.in
This post will illustrate how to create a database connection in C# using web.config file in MVC along with the reusable function for executing the stored procedure.


1. Create a connection string in web.config file or copy the code given below. Put this code in your <configuration> </configuration> part.


Populate drop down via AJAX using MVC4 C# when page loads.

1. Create a view that contains one drop down list for displaying items into it.

2. In Controller write a method that return JsonResult. And don't forget to mention it as [HttpPost]     since we will be using AJAX POST method, Ajax data type as Json hence the return type of             method is JsonResult.

3. We will create a function loadChannels() that will be called when the document is ready. This is        achieved using Jquery as :- 
      $(document).ready(function(){
               //Function call goes here.
      });

4. The method that we have written in controller (NOTE STEP 2) which will return JsonResult will     get called via AJAX from the method loadChannels() (NOTE STEP 3).



View as FpcDetails.cshtml

@{
    ViewBag.Title = "FpcDetails";
    Layout = "~/Views/Shared/_LayoutPrivate.cshtml";
}
@using (Html.BeginForm("FpcDetails", "Fpc", FormMethod.Post, new { enctype = "multipart/form-data", id = "form" }))
{
        <table>
            <tr>
                <td>
                    Select Channel:
                </td>
                <td>
                    @Html.DropDownList("channelsList", new List<SelectListItem> { }, string.Empty, new {                                                                   @class = "DropDown", @id = "dropDownChannels" }
                                                        )
                </td>
            </tr>
        </table>

    <input type="hidden" id="hdnChannels" />
}

//Document.ready function calling loadChannels().

<script type="text/javascript">

    $(document).ready(function () {
        loadChannels();
    });

/* Defining loadChannels() function */

    /*Loading channels on page load*/
 
  function loadChannels() {
        var options = {};
/* url for ajax to call a method GetChannels in the controller Fpc that will return JsonResult */

        options.url = '@Url.Action("GetChannels", "Fpc")';

/* Method type of Ajax is POST. Same will be mentioned in controller GetChannels() method as [HttpPost] */
        options.type = "POST";

/* Type of Ajax is json. This will  be the return type of method defined in Controller.i.e., JsonResult. */

        options.dataType = "json";
        options.contentType = "application/json";

/* channels passed as argument in the function as used to get the returned values from the controller back to       the view. This will give us an List of Id and Name. Hence we need to iterate over it in order to display           them. */

        options.success = function (channels) {

/* Empty the drop down list before appending any new values. */

            $("#dropDownChannels").empty();
            $("#dropDownChannels").append("<option value=></option>");
            for (var i = 0; i < channels.length; i++) {
                $("#dropDownChannels").append("<option value=" + channels[i].Id + ">" + channels[i].Name +                                                                           "</option>");
            }
            $("#dropDownChannels").prop("disabled", false);
        };

/* If there is any problem in Ajax, error method will get invoked. */

        options.error = function () { alert("Error retrieving Channels!"); };
        $.ajax(options);
    }

</script>


Controller: 

/* Inside our controller we just add the following code. */

/*Get all Channels via AJAX */
        [HttpPost]
        public JsonResult GetChannels()
        {
            List<AMSChannel> channels;
            channels = context.AMSChannels.ToList();
            var result = (from x in channels select new { Id = x.ChannelId, Name = x.ChannelName });
            return Json(result, JsonRequestBehavior.AllowGet);
        }