European ASP.NET MVC Hosting

BLOG about Latest ASP.NET MVC Hosting and Its Technology - Dedicated to European Windows Hosting Customer

ASP.NET MVC 6 Hosting Italy - HostForLIFE.eu :: How to Use Dapper.NET ORM in ASP.NET MVC ?

clock October 22, 2015 23:36 by author Peter

In this tutorial, let me explain you how to use Dapper.NET ORM in ASP.NET MVC 6. Dapper is a simple object mapper for .NET. Dapper is a file you can drop in to your project that will extend your IDbConnection interface. A key feature of dapper is performance. the subsequent metrics show how long it takes to execute five hundred select statements against a db and map the data returned to objects.

Now,  Install dapper using Nuget Package Manager
PM> Install-Package Dapper

After that, Create a project in ASP.NET MVC and then Add a folder named Dapper inside it as you can see on the following picture:

Next step: Create User and Address classes
public class Address
{
public int AddressID { get; set; }
public int UserID { get; set; }
public string AddressType { get; set; }
public string StreetAddress { get; set; }
public string City { get; set; }
public string State { get; set; }
public string ZipCode { get; set; }
}

public class User
{
public User()
{
this.Address = new List<Address>();
}

public int UserID { get; set; }

public string FirstName { get; set; }

public string LastName { get; set; }

public string Email { get; set; }

public List<Address> Address { get; set; }
}

Now Create IUserRepository.cs interface  and UserRepository.cs classes for data access.
public interface IUserRepository
{
List < User > GetAll();
User Find(int id);
User Add(User user);
User Update(User user);
void Remove(int id);
User GetUserInformatiom(int id);
}
public class UserRepository : IUserRepository
{
private IDbConnection _db = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);
public List<User> GetAll()
{
return this._db.Query<User>("SELECT * FROM Users").ToList();
}

public User Find(int id)
{
return this._db.Query<User>("SELECT * FROM Users WHERE UserID = @UserID", new { id }).SingleOrDefault();
}

public User Add(User user)
{
var sqlQuery = "INSERT INTO Users (FirstName, LastName, Email) VALUES(@FirstName, @LastName, @Email); " + "SELECT CAST(SCOPE_IDENTITY() as int)";
var userId = this._db.Query<int>(sqlQuery, user).Single();
user.UserID = userId;
return user;
}
public User Update(User user)
{
var sqlQuery =
    "UPDATE Users " +
    "SET FirstName = @FirstName, " +
    "    LastName  = @LastName, " +
    "    Email     = @Email " +
    "WHERE UserID = @UserID";
this._db.Execute(sqlQuery, user);
return user;
}

public void Remove(int id)
{
throw new NotImplementedException();
}

public User GetUserInformatiom(int id)
{
using (var multipleResults = this._db.QueryMultiple("GetUserByID", new { Id = id }, commandType: CommandType.StoredProcedure))
{
    var user = multipleResults.Read<User>().SingleOrDefault();

    var addresses = multipleResults.Read<Address>().ToList();
    if (user != null && addresses != null)
    {
        user.Address.AddRange(addresses);
    }

    return user;
}
}
}


Now use the above repository in the HomeController.cs
Create an instance for UserRepository class
private IUserRepository _repository = new UserRepository();

For Get All User write the following code:
public ActionResult Index()
{
return View(_repository.GetAll());
}

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 France - HostForLIFE.eu :: How to Avoid XSS (Cross Site-Scripting) in MVC Project

clock October 16, 2015 11:09 by author Rebecca

Cross-site scripting (XSS) is a type of computer security vulnerability typically found in web applications. XSS enables attackers to inject client-side script into web pages viewed by other users. Cross-Site Scripting (XSS) attacks are a type of injection, in which malicious scripts are injected into otherwise trusted web sites. In this article, I will show you how to avoid XSS while allowing only the HTML that you want to accept. In example, only <b> and <u> tags.

Firstly, let's filter the user input, and accept only <b></b> and <u></u> tags.

Step 1: Disables input validation

Step 2: Encodes all the input that is coming from the user

Step 3: Replace the encoded html with the HTML elements that you want to allow

Here is the full code snippet:

[HttpPost]
// Input validation is disabled, so the users can submit HTML
[ValidateInput(false)]
public ActionResult Create(Comment comment)
{
    StringBuilder sbComments = new StringBuilder();
   
    // Encode the text that is coming from comments textbox
    sbComments.Append(HttpUtility.HtmlEncode(comment.Comments));
   
    // Only decode bold and underline tags
    sbComments.Replace("&lt;b&gt;", "<b>");
    sbComments.Replace("&lt;/b&gt;", "</b>");
    sbComments.Replace("&lt;u&gt;", "<u>");
    sbComments.Replace("&lt;/u&gt;", "</u>");
    comment.Comments = sbComments.ToString();

    // HTML encode the text that is coming from name textbox
    string strEncodedName = HttpUtility.HtmlEncode(comment.Name);
    comment.Name = strEncodedName;

    if (ModelState.IsValid)
    {
        db.Comments.AddObject(comment);
        db.SaveChanges();
        return RedirectToAction("Index");
    }

    return View(comment);
}

This is just one example. Only filtering the user input can't guarantee XSS elimination. XSS can happen in different ways and forms.

Hope you did it!

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 Different Actions to Show A Single View

clock October 2, 2015 12:39 by author Rebecca

In this article, you will learn how use different actions to show a single view in ASP.NET MVC.  It’s common situation in project development where you don’t want to create view for each and every action of certain controller. In this situation, we have to use concept of shared view. The solution is very simple, you just have to keep the view in shared folder. Like below:

Now, The question is why need to keep in shared folder? The reason is when you run any controller, by default it check its own directory or shared directory. Every controller will look in shared directory, if it not available in it’s own directory. Let’s have a look on below code, let's create very simple controller class:

sing System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
 
namespace MVC3.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/
        public ActionResult Action1()
        {
          
            ViewBag.Controller = "Action1";
            return View("_Common");
        }
        public ActionResult Action2()
        {
          
            ViewBag.Controller = "Action2";
            return View("_Common");
        }
 
    }

Both Action1() and Action2() is calling _Common view and as the view is placed in shared folder, both can able to access. Before calling to view we are assigning action name in ViewBag. From view we can detect which action has invoked it. Here is code for view:

<%@ Page
Language="C#"
Inherits="System.Web.Mvc.ViewPage<MVC3.Models.customer>"
%>
<!DOCTYPE html>
<html>
<head runat="server">
    <title>_Common</title>
</head>
<body>
    <div>
        <% var ActionName = ViewBag.ActionName; %>
        <% if (ActionName == "Action1")
           {%>
          
              This view is called from Action 1
           <%}
           else
           {%>
          
              This view is Called from Action 2
           <%} %>
    </div>
</body>
</html>

 
Here is the output:

Now, the other question my show “Is it possible to call one view from different controller”? Yes, you can call. In below example, you will see how to do that.

You can call one view from different controller. This is your first controller Home1:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
 
namespace MVC3.Controllers
{
    public class Home1Controller : Controller
    {
        public ActionResult Action()
        {
          
            ViewBag.Controller = "Home1";
            return View("_Common");
        }
    }
}

And here is the output.



And for the Home2 controller:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
 
namespace MVC3.Controllers
{
    public class Home2Controller : Controller
    {
        public ActionResult Action()
        {
          
            ViewBag.Controller = "Home2";
            return View("_Common");
        }
 
    }
}

Here is the output:

 

It’s clear that both Action() (they are in different controller) are calling same 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 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.



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.



About HostForLIFE

HostForLIFE 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 2019 Hosting, ASP.NET 5 Hosting, ASP.NET MVC 6 Hosting and SQL 2019 Hosting.


Month List

Tag cloud

Sign in