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 Show SQL Server Database Update in ASP.NET MVC

clock September 22, 2015 12:19 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:

<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

Whenever 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 6 Hosting Italy - HostForLIFE.eu :: How to create Multi-Select Dropdown With Checkbox in ASP.NET MVC?

clock September 14, 2015 06:18 by author Peter

Today, I will show you how to creat Multi-Select Dropdown With Checkbox in ASP.NET MVC.
1. MVC set Viewdata in controller inside save get method using foreach loop.

2. Within view write foreach loop for multiselect dropdown with checkboxlist. And now, write the following code:
<div id="divStudentlist" style="height: 100px; overflow: auto; border: solid; width: 150px;"> 
@foreach (var items in ViewData["Items"] as List 
<SelectListItem>) { 
    <table width="100%"> 
    <tr> 
        <td width="20px"> 
            <input type="checkbox" value="@items.Value" class="chkclass" /> 
        </td> 
        <td width="100px"> 
            @items.Text 
        </td> 
    </tr> 
    </table> 
    } 
</div> 

3. Now the question arises, how will you send your chosen items values to controller as a result of once you get the values into the controller, you'll be able to do something like save into database. therefore let’s perceive the subsequent jQuery code. Before that, you must place @Html.Hidden("idlist") within Ajax.BeginForm and currently write jQuery code as you can see below:
var idslist = ""; 
$("input:checkbox[class=chkclass]").each(function() { 
if ($(this).is(":checked")) { 
    var userid = $(this).attr("value"); 
    idslist = idslist + userid + ','; 

}); 
$("#idlist").val(idslist); 


4. Inside controller add/save post technique ought to have the subsequent parameter: (FormCollection frm) and then write the subsequent c# code:
string[] i1; 
string items = frm["idlist"]; 
if (items != null) { 
i1 = items.Split(new [] { 
    "," 
}, StringSplitOptions.RemoveEmptyEntries); 
for (int i = 0; i < i1.Length; i++) { 
    string s = i1[i]; /*Inside string type s variable should contain items values */ 

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 Create a Hyperlink Between ASP.NET MVC Pages

clock September 11, 2015 11:53 by author Rebecca

In this article, we will discuss about generating hyperlinks using actionlink HTML helper for navigation between MVC pages.

For example, you want to display all the employees in a bulletted list as shown below. Notice that all the employee names are rendered as hyperlinks.

When the hyperlink is clicked, the user will be redirected to employee details page, displaying the full details of the employee as shown below:

Copy and paste the following Index() action method in EmployeeController class. This method retrieves the list of employees, which is then passed on to the view for rendering:

public ActionResult Index()
{
    EmployeeContext employeeContext = new EmployeeContext();
    List<Employee> employees = employeeContext.Employees.ToList();

    return View(employees);
}

At the moment, you don't have a view that can display the list of employees. To add the view, follow this instruction:

1. Right click on the Index() action method
2. Set

  • View name = Index
  • View engine = Razor

Select, Create a stronlgy-typed view checkbox
Select "Employee" from "Model class" dropdownlist
3. Click Add

At this point, "Index.cshtml" view should be generated. Copy and paste the following code in "Index.cshtml":

@model IEnumerable<MVCDemo.Models.Employee>

@using MVCDemo.Models;

<div style="font-family:Arial">
@{
    ViewBag.Title = "Employee List";
}

<h2>Employee List</h2>
<ul>
@foreach (Employee employee in @Model)
{
    <li>@Html.ActionLink(employee.Name, "Details", new { id = employee.EmployeeId })</li>
}
</ul>
</div>

Description:

  • @model is set to IEnumerable<MVCDemo.Models.Employee>
  • Your are using Html.ActionLink html helper to generate links

And the last, please copy and paste the following code in Details.cshtml:

@Html.ActionLink("Back to List", "Index")

Congrats, you're done!

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 Move Data using ViewData or ViewBag

clock September 8, 2015 08:38 by author Rebecca

This article deals with how you can move data from a controller to view. For that you can use either ViewData or ViewBag. Let's see how you can implement it:

Step 1: Adding Controller

1. First of all, we can add a control to the project as we already seen.

2. Give name to the controller and click on Add button.

Step 2: Using ViewData

Double click on the controller and add the following contents to controller.

Step 3: Adding View

1. Add a corresponding view for the controller.

2. By Double click on the view and add the following contents to view.

3. Saving and run the application, we will obtain the result. For example, it shows the current system date and time.

Step 4: Using ViewBag

1. Likewise we can also use ViewBag instead of ViewData.Same procedure repeat again.


2. Double click on the controller and add the following contents to controller.

3. Also by Double click on the view and add the following contents to view.

4. Then run the project and it will show the current system date and time.

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.



HostForLIFE.eu Proudly Launches ASP.NET 4.6 Hosting

clock September 7, 2015 12:36 by author Peter

HostForLIFE.eu was established to cater to an underserved market in the hosting industry; web hosting for customers who want excellent service. HostForLIFE.eu – a cheap, constant uptime, excellent customer service, quality, and also reliable hosting provider in advanced Windows and ASP.NET technology. HostForLIFE.eu proudly announces the availability of the ASP.NET 4.6 hosting in their entire servers environment.

http://hostforlife.eu/img/logo_aspnet1.png

ASP.NET is Microsoft's dynamic website technology, enabling developers to create data-driven websites using the .NET platform and the latest version is 5 with lots of awesome features. ASP.NET 4.6 is a lean .NET stack for building modern web apps. Microsoft built it from the ground up to provide an optimized development framework for apps that are either deployed to the cloud or run on-premises. It consists of modular components with minimal overhead.

According to Microsoft officials, With the .NET Framework 4.6, you'll enjoy better performance with the new 64-bit "RyuJIT" JIT and high DPI support for WPF and Windows Forms. ASP.NET provides HTTP/2 support when running on Windows 10 and has more async task-returning APIs. There are also major updates in Visual Studio 2015 for .NET developers, many of which are built on top of the new Roslyn compiler framework. The .NET languages -- C# 6, F# 4, VB 14 -- have been updated, too.There are many great features in the .NET Framework 4.6. Some of these features, like RyuJIT and the latest GC updates, can provide improvements by just installing the .NET Framework 4.6.

HostForLIFE.eu hosts its servers in top class data centers that is located in Amsterdam (NL), London (UK), Paris (FR), Frankfurt(DE) and Seattle (US) to guarantee 99.9% network uptime. All data center feature redundancies in network connectivity, power, HVAC, security, and fire suppression. All hosting plans from HostForLIFE.eu include 24×7 support and 30 days money back guarantee. The customers can start hosting their ASP.NET 4.6 site on their environment from as just low €3.00/month only.

HostForLIFE.eu is a popular online ASP.NET based hosting service provider catering to those people who face such issues. The company has managed to build a strong client base in a very short period of time. It is known for offering ultra-fast, fully-managed and secured services in the competitive market.

HostForLIFE.eu offers the latest European ASP.NET 4.6 hosting installation to all their new and existing customers. The customers can simply deploy their ASP.NET 4.6 website via their world-class Control Panel or conventional FTP tool. HostForLIFE.eu is happy to be offering the most up to date Microsoft services and always had a great appreciation for the products that Microsoft offers.

Further information and the full range of features ASP.NET 4.6 Hosting can be viewed here http://hostforlife.eu/European-ASPNET-46-Hosting



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