European ASP.NET MVC 4 and MVC 5 Hosting

BLOG about ASP.NET MVC 3, ASP.NET MVC 4, and ASP.NET MVC 5 Hosting and Its Technology - Dedicated to European Windows Hosting Customer

ASP.NET MVC 6 Hosting - HostForLIFE.eu :: How to Use jQuery and Bootstrap to Create Tree View

clock August 26, 2015 05:52 by author Rebecca

This article tells how to create a parent / child tree view in ASP.NET MVC using Bootstrap and jQuery. It is a practical approach so you can create an example in which you will create a parent object. The parent object will have associated child objects.

Step 1

You will create two classes, one is AuthorViewModel and another is BookViewModel. AuthorViewModel is the main class that has an association with the BookViewModel class. In other words each AuthorViewModel class object has a list of BookViewModel class objects. The following is the code snippet for the BookViewModel class.

namespace TreeView.Models  

    public class BookViewModel  
    { 
        public long Id  
        { 
            get; 
            set; 
        } 
        public string Title  
        { 
            get; 
            set; 
        } 
        public bool IsWritten  
        { 
            get; 
            set; 
        } 
    } 

}

The following is the code snippet for the AuthorViewModel class:


    using System.Collections.Generic; 
     
    namespace TreeView.Models { 
        public class AuthorViewModel  
        { 
            public AuthorViewModel()  
            { 
                BookViewModel = new List < BookViewModel > (); 
            } 
            public int Id  
            { 
                get; 
                set; 
            } 
            public string Name  
            { 
                get; 
                set; 
            } 
            public bool IsAuthor  
            { 
                get; 
                set; 
            } 
            public IList < BookViewModel > BookViewModel  
            { 
                get; 
                set; 
            } 
        } 
    }  

Step 2

Now, create a controller “HomeController” that has two action methods for both GET and POST requests. The action method's name is “Index”. The Get request action method returns a tree view in the UI whereas the POST request method gets the posted data from the UI. The following is the code snippet for HomeController.

    using System.Collections.Generic; 
    using System.Linq; 
    using System.Web.Mvc; 
    using TreeView.Models; 
     
    namespace TreeView.Controllers 
    { 
        public class HomeController : Controller 
        { 
            [HttpGet] 
            public ActionResult Index() 
            { 
                List<AuthorViewModel> model = new List<AuthorViewModel>(); 
     
                AuthorViewModel firstAuthor = new AuthorViewModel 
                { 
                    Id = 1, 
                    Name = "John", 
                    BookViewModel = new List<BookViewModel>{ 
                        new BookViewModel{ 
                            Id=1, 
                            Title = "JQuery", 
                            IsWritten = false 
                        }, new BookViewModel{ 
                            Id=1, 
                            Title = "JavaScript", 
                            IsWritten = false 
                        } 
                    } 
                }; 
     
                AuthorViewModel secondAuthor = new AuthorViewModel 
                { 
                    Id = 2, 
                    Name = "Deo", 
                    BookViewModel = new List<BookViewModel>{ 
                        new BookViewModel{ 
                            Id=3, 
                            Title = "C#", 
                            IsWritten = false 
                        }, new BookViewModel{ 
                            Id=4, 
                            Title = "Entity Framework", 
                            IsWritten = false 
                        } 
                    } 
                }; 
                model.Add(firstAuthor); 
                model.Add(secondAuthor); 
                return View("Index", model); 
            } 
     
            [HttpPost] 
            public ActionResult Index(List<AuthorViewModel> model) 
            { 
                List<AuthorViewModel> selectedAuthors = model.Where(a => a.IsAuthor).ToList(); 
                List<BookViewModel> selectedBooks = model.Where(a => a.IsAuthor) 
                                                    .SelectMany(a => a.BookViewModel.Where(b => b.IsWritten)).ToList(); 
                return View(); 
            } 
        }  

The preceding code shows how books are associated with an author in the GET action method and how to get a selected tree node (authors and books) in the POST request.

Step 3

Bootstrap CSS is already added to the application but we write a new custom CSS for the tree view design. The following is the code snippet for the tree CSS.

.tree li { 
        margin: 0px 0;   
        list-style-type: none; 
        position: relative; 
        padding: 20px 5px 0px 5px; 
    } 
     
    .tree li::before{ 
        content: ''; 
        position: absolute;  
        top: 0; 
        width: 1px;  
        height: 100%; 
        right: auto;  
        left: -20px; 
        border-left: 1px solid #ccc; 
        bottom: 50px; 
    } 
    .tree li::after{ 
        content: ''; 
        position: absolute;  
        top: 30px;  
        width: 25px;  
        height: 20px; 
        right: auto;  
        left: -20px; 
        border-top: 1px solid #ccc; 
    } 
    .tree li a{ 
        display: inline-block; 
        border: 1px solid #ccc; 
        padding: 5px 10px; 
        text-decoration: none; 
        color: #666;     
        font-family: 'Open Sans',sans-serif; 
        font-size: 14px; 
        font-weight :600; 
        border-radius: 5px; 
        -webkit-border-radius: 5px; 
        -moz-border-radius: 5px; 
    } 
     
    /*Remove connectors before root*/ 
    .tree > ul > li::before, .tree > ul > li::after{ 
        border: 0; 
    } 
    /*Remove connectors after last child*/ 
    .tree li:last-child::before{  
          height: 30px; 
    } 
     
    /*Time for some hover effects*/ 
    /*We will apply the hover effect the the lineage of the element also*/ 
    .tree li a:hover, .tree li a:hover+ul li a { 
        background: #dd4814; color: #ffffff; border: 1px solid #dd4814; 
    } 
    /*Connector styles on hover*/ 
    .tree li a:hover+ul li::after,  
    .tree li a:hover+ul li::before,  
    .tree li a:hover+ul::before,  
    .tree li a:hover+ul ul::before{ 
        border-color:  #dd4814; 
    } 
    .tree-checkbox{ 
        margin :4px !important; 
    } 
     
      
    .tree:before { 
        border-left:  1px solid #ccc; 
        bottom: 16px; 
        content: ""; 
        display: block; 
        left: 0; 
        position: absolute; 
        top: -21px; 
        width: 1px; 
        z-index: 1; 
    } 
     
    .tree ul:after { 
        border-top: 1px solid #ccc; 
        content: ""; 
        height: 20px; 
        left: -29px; 
        position: absolute; 
        right: auto; 
        top: 37px; 
        width: 34px; 
    } 
    *:before, *:after { 
        box-sizing: border-box; 
    } 
    *:before, *:after { 
        box-sizing: border-box; 
    } 
    .tree { 
        overflow: auto; 
        padding-left: 0px; 
        position: relative; 
    }  

Step 4

Now, create an Index view that renders in the browser and shows the tree view for the author and book. The following is the code snippet for the Index view.

    @model List 
    <TreeView.Models.AuthorViewModel> 
    @section head{ 
    @Styles.Render("~/Content/css/tree.css") 
    } 
        <div class="panel panel-primary"> 
            <div class="panel-heading panel-head">Author Book Tree View</div> 
            <div id="frm-author" class="panel-body"> 
    @using (Html.BeginForm()) 
    { 
     
                <div class="tree"> 
    @for (int i = 0; i < Model.Count(); i++) 
    { 
     
                    <ul> 
                        <li> 
                            <a href="#"> 
    @Html.CheckBoxFor(model => model[i].IsAuthor, new { @class = "tree-checkbox parent", @id = @Model[i].Id }) 
     
                                <label for=@i> 
                                    <strong>Author:</strong> 
    @Html.DisplayFor(model => model[i].Name) 
     
                                </label> 
                            </a> 
                            <ul> 
    @for (int j = 0; j < Model[i].BookViewModel.Count(); j++) 
    { 
    int k = 1 + j; 
    @Html.HiddenFor(model => model[i].BookViewModel[j].Id) 
     
                                <li> 
                                    <a href="#"> 
    @Html.CheckBoxFor(model => model[i].BookViewModel[j].IsWritten, new { @class = "tree-checkbox node-item", @iid = i + "" + j }) 
     
                                        <label for=@i@j> 
                                            <strong>Book @(k):</strong> @Html.DisplayFor(model => model[i].BookViewModel[j].Title) 
                                        </label> 
                                    </a> 
                                </li> 
     
    } 
     
                            </ul> 
                        </li> 
                    </ul> 
    } 
     
                </div> 
                <div class="form-group"> 
                    <div class="col-lg-9"></div> 
                    <div class="col-lg-3"> 
                        <button class="btn btn-success" id="btnSubmit" type="submit"> 
    Submit 
    </button> 
                    </div> 
                </div> 
    } 
     
            </div> 
        </div> 
     
    @section scripts{ 
    @Scripts.Render("~/Scripts/tree.js") 
    }

Step 5

Thereafter, you can create the JavaScript file tree.js with the following code:

 

(function($)  
    { 
        function Tree() { 
            var $this = this; 
     
            function treeNodeClick()  
            { 
                $(document).on('click', '.tree li a input[type="checkbox"]', function() { 
                    $(this).closest('li').find('ul input[type="checkbox"]').prop('checked', $(this).is(':checked')); 
                }).on('click', '.node-item', function() { 
                    var parentNode = $(this).parents('.tree ul'); 
                    if ($(this).is(':checked')) { 
                        parentNode.find('li a .parent').prop('checked', true); 
                    } else { 
                        var elements = parentNode.find('ul input[type="checkbox"]:checked'); 
                        if (elements.length == 0) { 
                            parentNode.find('li a .parent').prop('checked', false); 
                        } 
                    } 
                }); 
            }; 
     
            $this.init = function() { 
                treeNodeClick(); 
            } 
        } 
        $(function() { 
            var self = new Tree(); 
            self.init(); 
        }) 
    }(jQuery))  

Output

This figure shows the parent child (author-book) tree view:

HostForLIFE.eu ASP.NET MVC 6 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.



ASP.NET MVC 6 Hosting - HostForLIFE.eu :: How to Use Chart Helper to Display Graphical Data

clock August 20, 2015 06:24 by author Rebecca

In this tutorial, you will learn how to display data in graphical form using the Chart Helper in ASP.NET MVC. The “Chart Helper” can create chart images of different types with many formatting options and labels. It can create standard charts like area charts, bar charts, column charts, line charts, and pie charts, along with more specialized charts like stock charts. The data you display in a chart can be from an array, from the results returned from a database, or from data that’s in an XML file.

Step 1

Lets create new ASP.NET MVC application and name it to “MvcChartDemo” then add the below ProductSales model and DbContext class inside Models folder.

public class ProductSales
{
    public int Id { get; set; }

    public string Name { get; set; }

    public int Sales { get; set; }
}

public class SalesContext : DbContext
{
    public DbSet ProductSales { get; set; }
}

Step 2

Next, add the below connectionStrings in Web.config file:

<connectionStrings>
     <add name="SalesContext" providerName="System.Data.SqlClient" connectionString="Data Source=./SQLExpress;Initial Catalog=Test;Integrated Security=SSPI;" />
</connectionStrings>

Step 3

Next, create HomeController and add the Index action method. Also, create the /Views/Home/Index.cshtml view and replace the content with the following code:

Index.cshtml

@model IEnumerable<MvcChartDemo.Models.ProductSales>

@{
   ViewBag.Title = "Chart Helper Demo";
}

<h2>Chart Helper Demo</h2>
@{
var key = new Chart(width: 600, height: 400)
                  .AddTitle("Product Sales")
                  .AddSeries("Default",
                             xValue: Model, xField: "Name",
                             yValues: Model, yFields: "Sales")
                  .Write();
}

Here, we create the Chart using the following Chart Helpers method.

@{
var key = new Chart(width: 600, height: 400)
                 .AddTitle("Product Sales")
                 .AddSeries("Default",
                             xValue: Model, xField: "Name",
                             yValues: Model, yFields: "Sales")
                 .Write();
}

The code first creates a new chart and sets its width and height. You specify the chart title by using the AddTitle method. To add data, you use the AddSeries method. In this example, you use the name, xValue, and yValues parameters of the AddSeries method. The name parameter is displayed in the chart legend. The xValue parameter contains an array of data that is displayed along the horizontal axis of the chart. The yValues parameter contains an array of data this is used to plot the vertical points of the chart.

The Write method actually renders the chart. In this case, because you did not specify a chart type, the Chart helper renders its default chart, which is a column chart.

Now, run the application and you will see below output:

Step 4

You can change the Chart Type by defines chartType parameter of chart inside AddSeries method:

@{
var key = new Chart(width: 600, height: 400)
                  .AddTitle("Product Sales")
                  .AddSeries(chartType: "Pie",
                             xValue: Model, xField: "Name",
                             yValues: Model, yFields: "Sales")
                  .Write();
}

HostForLIFE.eu ASP.NET MVC 6 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.

 



ASP.NET MVC 6 Hosting - HostForLIFE.eu :: How to Use Adaptor to Create 3D Image Slider in ASP.NET MVC

clock August 18, 2015 06:20 by author Rebecca

In this article, I will tell you how create a Responsive jQuery 3D Content Image Slider in ASP.NET MVC using Adaptor. You can find the plugin here. Adaptor content slider aims to provide a simple interface for developers to create cool 2D or 3D slide animation transitions.

Follow these steps to create 3D content image slider in ASP.NET MVC:

Step 1

Create a new project in ASP.NET MVC named JQueryImageSlider. After that copy the css, img, js folders and paste in JQueryImageSlider project.

 

Step 2

In the _Layout.cshtml page reference the Adaptor 3D slider files:

Step 3

Now create class models ImageModel that holds images from database:

public class ImageModel
{
    public int ImageID { get; set; }
    public string ImageName { get; set; }
    public string ImagePath { get; set; }
}

Step 4

Get the images list from the repository and bind it to slider:

public ActionResult Index()
{
   //Bind it from the repository
   List imageList = new List();
   imageList.Add(new ImageModel { ImageID = 1, ImageName = "Image 1", ImagePath = "/img/the-battle.jpg" });
   imageList.Add(new
      ImageModel { ImageID = 2, ImageName = "Image 2", ImagePath = "/img/hiding-the-map.jpg"
   });
   imageList.Add(new ImageModel { ImageID = 3, ImageName = "Image 3", ImagePath = "/img/theres-the-buoy.jpg" });
   imageList.Add(new ImageModel { ImageID = 4, ImageName = "Image 4", ImagePath = "/img/finding-the-key.jpg" });
   imageList.Add(new ImageModel { ImageID = 5, ImageName = "Image 5", ImagePath = "/img/lets-get-out-of-here.jpg"});
   return View(imageList);
}

Step 5

In the View page add the following code:

<div id="viewport-shadow">
    <a href="#" id="prev" title="go to the next slide"></a>
    <a href="#" id="next" title="go to the next slide"></a>
    <div id="viewport">
        <div id="box">
            @*Bind images here*@
            @foreach (var item in Model)
            {
                <figure class="slide">
                    <img [email protected]>
                </figure>
            }


        </div>
    </div>
    <div id="time-indicator"></div>
</div>

@* here we are binding the slider controls navigation *@
<footer>
    <nav class="slider-controls">
        <ul id="controls">
            @{int index = 0;}
            @foreach (var item in Model)
            {
               
                 string cssClass = index.Equals(0) ? "goto-slide current" : "goto-slide";

                 <li><a class="@cssClass" href=" #" data-slideindex="@index"></a></li>
                 index= index +1;
            }
         
        </ul>
    </nav>
</footer>

Step 6

We can also add the caption for image slider using the figcaption tag:

<figure class="slide">
    <img [email protected] class="img-responsive">
    <figcaption>Static Caption</figcaption>
</figure>

HostForLIFE.eu ASP.NET MVC 6 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.



ASP.NET MVC 6 Hosting - HostForLIFE.eu :: How to Use SignalR & SQL Dependency to Display Updates from SQL Server

clock August 13, 2015 06:05 by author Rebecca

In this post, you will learn how to display real time updates from the  SQL Server  by using SignalR  and SQL Dependency in ASP.NET MVC.

The following are the steps that we need to enable in the SQL Server first.

Step 1 - Enable Service Broker on the database

The following is the query that need to enable the service broker:

ALTER DATABASE BlogDemos SET ENABLE_BROKER WITH ROLLBACK IMMEDIATE ;

Step 2 - Add Connection string to the Web.Config file

<add name=”DefaultConnection” connectionString=”Server=servername;Database=databasename;User Id=userid;Password=password;” providerName=”System.Data.SqlClient” />

Step 3 - Enable SQL Dependency

In Global.asax start the SQL Dependency in App_Start() event and Stop SQL dependency in the Application_End() event:

public class MvcApplication : System.Web.HttpApplication
    {
        string connString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;

        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            GlobalConfiguration.Configure(WebApiConfig.Register);
            //Start SqlDependency with application initialization
            SqlDependency.Start(connString);
        }

        protected void Application_End()
        {
            //Stop SQL dependency
            SqlDependency.Stop(connString);
        }
    }

Step 4 - Install SignalR from The Nuget

Run the following command in the Package Manager Console:

Install-Package Microsoft.AspNet.SignalR

Step 5 - Create SignalR Hub Class

Create MessagesHub class in the Hubs folder:

public class MessagesHub : Hub
    {
        private static string conString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ToString();
        public void Hello()
        {
            Clients.All.hello();
        }

        [HubMethodName("sendMessages")]
        public static void SendMessages()
        {
            IHubContext context = GlobalHost.ConnectionManager.GetHubContext<MessagesHub>();
            context.Clients.All.updateMessages();
        }  
    }

Step 6 - Get the  Data from the Repository

Create MessagesRepository to get the messages from the database when data is updated.

public class MessagesRepository
    {
        readonly string _connString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;

        public IEnumerable<Messages> GetAllMessages()
        {
            var messages = new List<Messages>();
            using (var connection = new SqlConnection(_connString))
            {
                connection.Open();
                using (var command = new SqlCommand(@"SELECT [MessageID], [Message], [EmptyMessage], [Date] FROM [dbo].[Messages]", connection))
                {
                    command.Notification = null;

                    var dependency = new SqlDependency(command);
                    dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);

                    if (connection.State == ConnectionState.Closed)
                        connection.Open();

                    var reader = command.ExecuteReader();

                    while (reader.Read())
                    {
                        messages.Add(item: new Messages { MessageID = (int)reader["MessageID"], Message = (string)reader["Message"], EmptyMessage =  reader["EmptyMessage"] != DBNull.Value ? (string) reader["EmptyMessage"] : "", MessageDate = Convert.ToDateTime(reader["Date"]) });
                    }
                }
             
            }
            return messages;
          
           
        }

        private void dependency_OnChange(object sender, SqlNotificationEventArgs e)
        {
            if (e.Type == SqlNotificationType.Change)
            {
                MessagesHub.SendMessages();
            }
        }
    }

Step 7 - Register SignalR at Startup Class

Add the following code:

app.MapSignalR();

Step 8 - View Page

Create div messagesTable that will append the table data from the database:

<div class="row">
    <div class="col-md-12">
       <div id="messagesTable"></div>
    </div>
</div>

Now Add the SignalR related scripts in the page >> getAllMessages is a function that return the partialview data and bind it into the messagesTable div.

<script src="/Scripts/jquery.signalR-2.1.1.js"></script>
 <!--Reference the autogenerated SignalR hub script. -->
    <script src="/signalr/hubs"></script>

<script type="text/javascript">
    $(function () {
        // Declare a proxy to reference the hub.
        var notifications = $.connection.messagesHub;
      
        //debugger;
        // Create a function that the hub can call to broadcast messages.
        notifications.client.updateMessages = function () {
            getAllMessages()
          
        };
        // Start the connection.
        $.connection.hub.start().done(function () {
            alert("connection started")
            getAllMessages();
        }).fail(function (e) {
            alert(e);
        });
    });


    function getAllMessages()
    {
        var tbl = $('#messagesTable');
        $.ajax({
            url: '/home/GetMessages',
            contentType: 'application/html ; charset:utf-8',
            type: 'GET',
            dataType: 'html'
        }).success(function (result) {
            tbl.empty().append(result);
        }).error(function () {
           
        });
    }
</script>

Step 9 - Create Partial View Page

Create a partial view _MessagesList.cshtml that returns all the messages:

@model IEnumerable<SignalRDbUpdates.Models.Messages>

<p>
    @Html.ActionLink("Create New", "Create")
</p>
<table class="table">
    <tr>
        <th>@Html.DisplayNameFor(model => model.MessageID)</th>
        <th>
            @Html.DisplayNameFor(model => model.Message)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.EmptyMessage)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.MessageDate)
        </th>
       
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.MessageID)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Message)
        </td>
        <th>
            @Html.DisplayFor(modelItem => item.EmptyMessage)
        </th>
        <td>
            @Html.DisplayFor(modelItem => item.MessageDate)
        </td>
       
    </tr>
}
</table>

Step 10 - Set Up the Database

Create the database called blogdemos and run the following script:

USE [BlogDemos]
GO
/****** Object:  Table [dbo].[Messages]    Script Date: 10/16/2014 12:43:55 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Messages](
    [MessageID] [int] IDENTITY(1,1) NOT NULL,
    [Message] [nvarchar](50) NULL,
    [EmptyMessage] [nvarchar](50) NULL,
    [Date] [datetime] NULL,
 CONSTRAINT [PK_Messages] PRIMARY KEY CLUSTERED
(
    [MessageID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[Messages] ADD  CONSTRAINT [DF_Messages_Date]  DEFAULT (getdate()) FOR [Date]
GO

Step 11 - Run the project

When eve data is inserted into the table the dependency_OnChange method will fire.

HostForLIFE.eu ASP.NET MVC 6 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.



ASP.NET MVC Hosting - HostForLIFE.eu :: How to List Data from Database Into Grid

clock June 27, 2015 11:25 by author Rebecca

In this article, you are going to learn how to quickly list the data from the database into Grid in ASP.NET MVC. We all know the benefit and beauty of GridView in ASP.NET Web Form. This is the best data control in ASP.NET MVC to quickly list the data from the database without specifying columns, table format etc. This was missing in ASP.NET MVC as it has not server side control like GridView.

The good thing here is that you can still use the GridView of System.Web.UI.WebControls namespace in ASP.NET MVC and populate with data and get it rendered in the ASP.NET MVC view. Here is how the action method looks like:

The Controller

public ActionResult ListDataInGridView()

        {

            System.Web.UI.WebControls.GridView gView =

                new System.Web.UI.WebControls.GridView();

            gView.DataSource = db.PersonalDetails.ToList();

            gView.DataBind();


            using (System.IO.StringWriter sw = new System.IO.StringWriter())

            {

                using (System.Web.UI.HtmlTextWriter htw = new System.Web.UI.HtmlTextWriter(sw))

                {

                    gView.RenderControl(htw);

                    ViewBag.GridViewString = sw.ToString();

                }

            }

            return View();

        }

In this action method, you have first instantiated the GridView control and set its data source and called DataBind method that will bind the data from the data source. 

Next, you have to use StringWriter and HtmlTextWriter to render the GridView content string into the StringWriter. The same is being set to the ViewBag.GridViewString.

The View

The View looks like below that simply use @Html.Raw method to write the content of the ViewBag:

@{ ViewBag.Title = "ListDataInGridView"; }

<h2>List Data In GridView</h2>

@Html.Raw(ViewBag.GridViewString)

Using @Html.Raw method is important as without this, it will simply render the HTML encoded characters of the GridView content string.

HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.



ASP.NET MVC 6 Hosting - HostForLIFE.eu :: How to Use Dropzone.js and HTML to Upload File in ASP.NET MVC

clock June 26, 2015 06:19 by author Rebecca

In this article, you can learn how to file upload in ASP.NET MVC using Dropzone.js and HTML5. Dropzone.js is an open source library that provides drag and drop file uploads with image previews. It’s lightweight, doesn’t depend on any other library (like jQuery) and is highly customizable. Follow these steps to upload your file using Dropzone.js and HTML.

Step 1

Before jumping to the project, first you will download the Dropzone.js files. You can download the latest version from the official site here http://www.dropzonejs.com/ and also you can install using the nuget package manage console by the following command Package Manager Console:

PM> Install-Package dropzone

In this tutorial, I'm using the nuget command to install Dropzone.js:

Step 2

Next is file upload implementation. You have to create a default ASP.NET MVC Web Application after you have installed the Dropzone.js. Then, create a bundle for your script file in BundleConfig.cs:

bundles.Add(new ScriptBundle("~/bundles/dropzonescripts").Include(
                     "~/Scripts/dropzone/dropzone.js"));

Step 3

Similarly you can add the Dropzone stylesheet in the BundleConfig.cs:

bundles.Add(new StyleBundle("~/Content/dropzonescss").Include(
                     "~/Scripts/dropzone/css/basic.css",
                     "~/Scripts/dropzone/css/dropzone.css"));

Step 4

Now add the bundle reference in your _Layout page:

Step 5

Everything is fine, you can start writing up the application code. Now go to /Home/Index.cshtml file and Dropzone form in the page using this code:

div class="jumbotron">
    <form action="~/Home/SaveUploadedFile" method="post" enctype="multipart/form-data" class="dropzone" id="dropzoneForm" style="width: 50px; background: none; border: none;">
        <div class="fallback">
            <input name="file" type="file" multiple />
            <input type="submit" value="Upload" />
        </div>
    </form>
</div>

Step 6

Now open the HomeController.cs and add the following code as follows:

public ActionResult SaveUploadedFile()
        {
            bool isSavedSuccessfully = true;
            string fName = "";
                    try{
            foreach (string fileName in Request.Files)
            {
                HttpPostedFileBase file = Request.Files[fileName];
                //Save file content goes here
                fName = file.FileName;
                if (file != null && file.ContentLength > 0)
                {

                    var originalDirectory = new DirectoryInfo(string.Format("{0}Images\\WallImages", Server.MapPath(@"\")));

                    string pathString = System.IO.Path.Combine(originalDirectory.ToString(), "imagepath");

                    var fileName1 = Path.GetFileName(file.FileName);

                    bool isExists = System.IO.Directory.Exists(pathString);

                    if (!isExists)
                        System.IO.Directory.CreateDirectory(pathString);

                    var path = string.Format("{0}\\{1}", pathString, file.FileName);
                    file.SaveAs(path);

                }

            }
                       
           }
           catch(Exception ex)
            {
                isSavedSuccessfully = false;
            }


            if (isSavedSuccessfully)
            {
                return Json(new { Message = fName });
            }
            else
            {
                return Json(new { Message = "Error in saving file" });
            }
        }

Step 7

Then, add the following script to your Index.cshtml page:

//File Upload response from the server
        Dropzone.options.dropzoneForm = {
            init: function () {
                this.on("complete", function (data) {
                    //var res = eval('(' + data.xhr.responseText + ')');
                     var res = JSON.parse(data.xhr.responseText);
                });
            }
        };

Also add the following css:

#dropZone {
        background: gray;
        border: black dashed 3px;
        width: 200px;
        padding: 50px;
        text-align: center;
        color: white;
    }

Now, you have uploaded your file using Dropzone.js and HTML5.

HostForLIFE.eu ASP.NET MVC 6 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.



ASP.NET MVC 6 Hosting - HostForLIFE.eu :: How to Deploy Google ReCAPTCHA in ASP.NET MVC

clock June 22, 2015 06:48 by author Rebecca

Here in this tutorial, I will explain about how to use Google reCAPTCHA in ASP.NET MVC. 

What is reCAPTCHA? reCAPTCHA protects the websites you love from spam and abuse. Google has updated thier reCAPTCHA API  to 2.0 . Now, users can now attest they are human without having to solve a CAPTCHA. Instead with just a single click they’ll confirm they are not a robot and it is called as “No CAPTCHA reCAPTCHA“.  This is how new reCAPTCHA look as follows:

Getting Google ReCAPTCHA

Now, lets create an API key pair for your site at https://www.google.com/recaptcha/intro/index.html and click on Get reCAPTCHA at top of the page and follow the below steps to create an application.

 

Once you have done with registration, the following keys will be generated:

  • Site key : is used to display the widget in your page or code.
  • Secret key: can be used as communication between your site and Google to verify the user response whether the reCAPTCHA is valid or not.

The next is to display the reCAPTCHA widget in your site.

Displaying Widget

We can render the Google reCAPTCHA widget in two ways as:

  1.     Automatically render the widget
  2.     Explicitly render the widget

For this example we will use Automatically render the widget in your page.

First load the script reference:

<script src="https://www.google.com/recaptcha/api.js" async defer></script>

Now, you need generate a DIV element with class name as g-recaptcha and your site key in the data-site key attribute in your webpage to generate reCAPTCHA.

<div class="g-recaptcha" data-sitekey="your_site_key"></div>

Now, implement above code in Home/Index.cshtml view page.

<div class="row">
    <div class="col-md-12">
        <form action="/home/validatecaptcha" method="POST">
            <div class="g-recaptcha" data-sitekey="6LfiS_8SAAAAABvF6ixcyP5MtsevE5RZ9dTorUWr"></div>
            <br />
            <input type="submit" value="Submit">
        </form>
    </div>

 
</div>
@section scripts{
   <script src="https://www.google.com/recaptcha/api.js" async defer></script>
}

Verifying User Response

Once reCAPTCHA is generated  and solved by a end user, a field with g-recaptcha-response will be populated in the html. When ever user submit the form on your site, you can POST the parameter g-recaptcha-response to verify the user response. The following API url is used to verify the user response.

https://www.google.com/recaptcha/api/siteverify?secret=your_secret&response=response_string&remoteip=user_ip_address

In above API url the secret and response parameters are required and where as remoteip is optional. Here secret represents the Secret Key that was generated in the key pair and the repsonse is the g-recaptcha-response that was submitted during the form post. The following is the API JSON response object that we get once the response is submitted.

{
  "success": true|false,
  "error-codes": [...]   // optional
}

Next, you will create an response class to verify the user response:

public class CaptchaResponse
{
    [JsonProperty("success")]
    public bool Success { get; set; }

    [JsonProperty("error-codes")]
    public List<string> ErrorCodes { get; set; }
}

Then, you can create a POST method in Index action in the Home controller to verify the user response.

[HttpPost]
public ActionResult ValidateCaptcha()
{
    var response = Request["g-recaptcha-response"];
    //secret that was generated in key value pair
    const string secret = "YOUR KEY VALUE PAIR";

    var client = new WebClient();
    var reply =
        client.DownloadString(
            string.Format("https://www.google.com/recaptcha/api/siteverify?secret={0}&response={1}", secret, response));

    var captchaResponse = JsonConvert.DeserializeObject<CaptchaResponse>(reply);

    //when response is false check for the error message
    if (!captchaResponse.Success)
    {
        if (captchaResponse.ErrorCodes.Count <= 0) return View();

        var error = captchaResponse.ErrorCodes[0].ToLower();
        switch (error)
        {
            case ("missing-input-secret"):
                ViewBag.Message = "The secret parameter is missing.";
                break;
            case ("invalid-input-secret"):
                ViewBag.Message = "The secret parameter is invalid or malformed.";
                break;

            case ("missing-input-response"):
                ViewBag.Message = "The response parameter is missing.";
                break;
            case ("invalid-input-response"):
                ViewBag.Message = "The response parameter is invalid or malformed.";
                break;

            default:
                ViewBag.Message = "Error occured. Please try again";
                break;
        }
    }
    else
    {
        ViewBag.Message = "Valid";
    }

    return View();
}

That's all! Hope it works for you!

HostForLIFE.eu ASP.NET MVC 6 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.



ASP.NET MVC 6 Hosting - HostForLIFE.eu :: How to Return JavaScript Content from The Controller

clock June 19, 2015 06:50 by author Rebecca

In this tutorial, we're gonna discuss about how to return JavaScript Content from controller action method. I have created a demonstration here, let's follow it step by step.

Step 1

Create a controller action method that returns a view:

public ActionResult OutputJavaScript()
  {
      return View();
  }

View for above action method:

@{
    ViewBag.Title = "OutputJavaScript";
}

<h2>OutputJavaScript</h2>

Try clicking on the link below <br />

@Html.ActionLink("Test JavaScript", "OutputJavaScriptAlert)

Step 2

The view appears in the browser like below:

Notice the 2nd parameter of the ActionLink method, this is the action method name of the controller. When the link “Test JavaScript” is clicked, it calls the OutputJavaScriptAlert action method of the controller.

Step 3

Controller code:

public JavaScriptResult OutputJavaScriptAlert()
  {
      string a = "alert('this is alert')";
      return JavaScript(a);
  }


This action method returns JavaScript content that we get it in the new window or to download as displayed in the above picture (depending on the browser).

In general, these methods are used in the Ajax methods to return partial content.

HostForLIFE.eu ASP.NET MVC 6 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.



ASP.NET MVC 6 Hosting - HostForLIFE.eu :: How to Use HTML Helper to Generate a DropDownList in ASP.NET MVC

clock June 15, 2015 07:24 by author Rebecca

A dropdownlist in MVC is a collection of SelectListItem objects. Depending on your project requirement you may either hard code the values in code or retrieve them from a database table. In this tutorial, I will show you how to generate a dropdownlist using DropDownList html helper based on both approaches.

Generating a DropDownList using Hard Coded Values

You will use the following overloaded version of "DropDownList" HTML helper.
DropDownList(string name, IEnumerable<SelectListItem> selectList, string optionLabel)

The following code will generate a departments dropdown list. The first item in the list will be "Select Department".
@Html.DropDownList("Departments", new List<SelectListItem>
{
    new SelectListItem { Text = "IT", Value = "1", Selected=true},
    new SelectListItem { Text = "HR", Value = "2"},
    new SelectListItem { Text = "Payroll", Value = "3"}
}, "Select Department")

The downside of hard coding dropdownlist values with-in code is that, if we have to add or remove departments from the dropdownlist, the code needs to be modified.

Retrieve DropDownList from A Database Table

Pass list of Departments from the controller, then store them in "ViewBag"

public ActionResult Index()
{
    // Connect to the database
    SampleDBContext db = new SampleDBContext();
    // Retrieve departments, and build SelectList
    ViewBag.Departments = new SelectList(db.Departments, "Id", "Name");
           
    return View();
}

Now in the "Index" view, you can access Departments list from "ViewBag"
@Html.DropDownList("Departments", "Select Department")

HostForLIFE.eu ASP.NET MVC 6 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.



ASP.NET MVC 6 Hosting - HostForLIFE.eu :: How to Detect Errors in View at ASP.NET MVC

clock June 12, 2015 08:49 by author Rebecca

In this tutorial, I will tell you about detecting errors in views at compile-time rather than at run-time.

The following code will display employee's FullName and Gender. Here we are working with a strongly typed view. Employee is the model class for this view. This class has got "FullName" and "Gender" properties.

@model MVCDemo.Models.Employee
<fieldset>
    <legend>Employee</legend>

    <div class="display-label">
         @Html.DisplayNameFor(model => model.FullName)
    </div>
    <div class="display-field">
        @Html.DisplayFor(model => model.FullName)
    </div>

    <div class="display-label">
         @Html.DisplayNameFor(model => model.Gender)
    </div>
    <div class="display-field">
        @Html.DisplayFor(model => model.Gender)
    </div>
</fieldset>

For example, if you mis-spell FullName property as shown below, and when you compile the project, you wouldn't get any compile time errors.

@Html.DisplayNameFor(model => model.FullName1)

You will only come to know, about the error when the page crashes at run-time. If you want to enable compile time error checking for views in MVC, please folow this step:

1. Open MVC project file using a notepad. Project files have the extension of .csproj or .vbproj
2. Search for MvcBuildViews under PropertyGroup. MvcBuildViews is false by default. Turn this to true as shown below.
<MvcBuildViews>true</MvcBuildViews>
3. Save the changes.

If you now build the project, you should get compile time error.

HostForLIFE.eu ASP.NET MVC 6 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.



About HostForLIFE.eu

HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

We have offered the latest Windows 2016 Hosting, ASP.NET Core 2.2.1 Hosting, ASP.NET MVC 6 Hosting and SQL 2017 Hosting.


Tag cloud

Sign in