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 Russia - HostForLIFE.eu :: How to show Multiple Models in a Single View Using Dynamically Created Object ?

clock April 9, 2015 08:11 by author Scott

In this article I will disclose about How to show Multiple Models in a Single View utilizing dynamically created object in ASP.NET MVC. Assume I have two models, Course and Student, and I have to show a list of courses and students within a single view. By what means would we be able to do this? And here is the code that I used:

Model(Student.cs)
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace MVCMultipleModelsinView.Models
{
    public class Student
    {
        public int studentID { get; set; }
        public string studentName { get; set; }
        public string EnrollmentNo { get; set; }
        public string courseName { get; set; }
        public List<Student> GetStudents()
        {
            List<Student> students = new List<Student>();
            students.Add(new Student { studentID = 1, studentName = "Peter", EnrollmentNo = "K0001", courseName ="ASP.NET"});
            students.Add(new Student { studentID = 2, studentName = "Scott", EnrollmentNo = "K0002", courseName = ".NET MVC" });
            students.Add(new Student { studentID = 3, studentName = "Rebecca", EnrollmentNo = "K0003", courseName = "SQL Server" });
            return students;
        }
    }
}


Model(Course.cs):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace MVCMultipleModelsinView.Models
{
    public class Course
    {
        public int courseID { get; set; }
        public string courseCode { get; set; }
        public string courseName { get; set; }
        public List<Course> GetCourses()
        {
            List<Course> Courses = new List<Course>();
            Courses.Add(new Course { courseID = 1, courseCode = "CNET", courseName = "ASP.NET" });
            Courses.Add(new Course { courseID = 2, courseCode = "CMVC", courseName = ".NET MVC" });
            Courses.Add(new Course { courseID = 3, courseCode = "CSVR", courseName = "SQL Server" });
            return Courses;
        }
    }
}


Controller (CourseStudentController.cs):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Dynamic;
using MVCMultipleModelsinView.Models;
namespace MVCMultipleModelsinView.Controllers
{
    public class CourseStudentController : Controller
   {
        public ActionResult Index()
        {
            ViewBag.Message = "Welcome!";
            dynamic model = new ExpandoObject();
            Student stu = new Student();
            model.students = stu.GetStudents();
            Course crs = new Course();
            model.courses = crs.GetCourses();
            return View(model);
       }
    }
}

View(Index.cshtml):
@using MVCMultipleModelsinView.Models;
@{
   ViewBag.Title = "Index";
}
<h2>@ViewBag.Message</h2>
<style type="text/css">
table
    {
        margin: 4px;
        border-collapse: collapse;
        width: 500px;
        font-family:Tahoma;
   }
    th
    {
        background-color: #990000;
        font-weight: bold;
        color: White !important;
    }
    table th a
    {
        color: White;
        text-decoration: none;
    }
    table th, table td
    {
        border: 1px solid black;
        padding: 5px;
    }
</style>
<p>
    <b>Student List</b></p>
<table>
    <tr>
        <th>
            Student Id
        </th>
        <th>
            Student Name
        </th>
        <th>
            Course Name
        </th>
        <th>
            Enrollment No
        </th>
    </tr>
    @foreach (Student stu in Model.students)
    {
        <tr>
            <td>@stu.studentID
            </td>
            <td>@stu.studentName
            </td>
            <td>@stu.courseName
            </td>
            <td>@stu.EnrollmentNo
            </td>
        </tr>
    }
</table>
<p> 
 <b>Course List</b></p>
<table>
   <tr>
       <th>
            Course Id
        </th>
        <th>
            Course Code
        </th>
        <th>
            Course Name
       </th>
    </tr>
    @foreach (Course crs in Model.courses)
    {
        <tr>
            <td>@crs.courseID
            </td>
            <td>@crs.courseCode
            </td>
            <td>@crs.courseName
        </tr>
    }
</table>

HostForLIFE.eu ASP.NET MVC 6.0 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 UK - HostForLIFE.eu :: How to Search Records with Ajax in ASP.NET MVC ?

clock March 13, 2015 07:17 by author Peter

Today, I will tell you about how to search records in MVC with Ajax and jQuery. This code will filter out all matching records group by table column name.

First thing that you should do is create an empty ASP.NET MVC project. Now, add two class to your model. Employee and DemoContext and write the following code:
namespace SearchingDemo.Models
{
    public class Employee
    {
        [Key]
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Position { get; set; }
     }
}
namespace SearchingDemo.Models
{
    public class DemoContext : DbContext
    {
        public DbSet<Employee> Employees { get; set; }
    }
}

Add a Home Controller. Now, Add index Action to controller. and create corresponding view.
public ActionResult Index()
       {
           return View();
      }

Now, write the following code to Index View.
<link href="~/Content/Style.css" rel="stylesheet" />
<script src="~/Content/jquery-2.1.1.min.js"></script>
<script src="~/Content/CustomJs.js"></script>
<h2>Seaching Demo</h2> 
<div class="divFind">
    <table>
        <tr>
            <td>
                <input type="text" id="txtSearch" />
            </td>
            <td>
                <input type="button" id="btnSearch" value="Seach" />
            </td>
        </tr>
    </table>
</div>
<div id="divList"> 
</div>

Write the .JS code for click event on seach button to get filtered result. add following .JS code.
$(document).ready(function () {
    $('#btnSearch').on('click', function () {
        var getkey = $('#txtSearch').val();
        $.ajax({           
        type: 'POST',
            contentType: 'application/json; charset=utf-8',
            url: 'Home/Search',
            data: "{ 'searchKey':' " + getkey + "' }",
            success: function (data) {
                BindData(data);
            },            
            error: function (data) {
                alert('Error in getting result');
            }
        });
   });
}); 
function BindData(data) {
    var ulList = '<ul>';
    var resultType = ["FirstName", "LastName", "Position"];
    $.each(data, function (i, d) {
        ulList += '<li class="SeachType">' + resultType[i] + '</li>';
        if (d.length > 0) {
            $.each(d, function (key, value) {
                ulList += '<li>' + value.FirstName + ' - ' + value.LastName + ' - ' + value.Position + '</li>'
            });
        } else {            
        ulList += '<li><span class="red">No Results</span></li>';
        }
    });
    ulList += '</ul>'
    $('#divList').html(ulList);
}

Javascript code calling search function, which is written in controller. Add search function to your controller.
public JsonResult Search(string searchKey)
       {
           DemoContext dbObj = new DemoContext();
           var getKey = searchKey.Trim();
           var getFirstName = dbObj.Employees.Where(n => n.FirstName.Contains(getKey)).ToList(); 
           var getLastName = dbObj.Employees.Where(n => n.LastName.Contains(getKey)).ToList(); 
           var getPostion = dbObj.Employees.Where(n => n.Position.Contains(getKey)).ToList(); 
           IList<IList<Employee>> getTotal = new List<IList<Employee>>();
           getTotal.Add(getFirstName);
           getTotal.Add(getLastName);
           getTotal.Add(getPostion);
           int count = getTotal.Count();
           return Json(getTotal);
      }

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 Germany - HostForLIFE.eu :: How to Display Empty Data Text in WebGrid in ASP.NET MVC

clock March 6, 2015 06:57 by author Peter

In this case we disclose that how to show Empty Data Text in webgrid in MVC with ASP.NET.

There is no facility in webgrid to show empty datatext automatically, so we need to manually write or characterize the code for this.

Let's see a simple tips that demonstrates to show Empty Data or unfilled information message in ASP.NET MVC WebGrid by utilizing WebGrid web helper class. Here in this post we will check the  model in the event that it  has no data then show a message, like the EmptyDataText property of the ASP.NET GridView.

To utilize the WebGrid web assistant as a part of MVC application, you need to first make an article reference to the WebGrid class and utilize the GetHtml() method that renders the grid. To use the WebGrid web helper in mvc application, you have to first create an object reference to the WebGrid class and use the GetHtml() method that renders the grid.
@{
                Var grid=new WebGrid(Model);
@grid.GetHtml();
}
To Display an Empty Data Text in Webgrid when the Model has no data or no record, just you have to write  following one:
@if(Model.Count>0)
@{
Var grid=new WebGrid(Model);
@grid.GetHtml();
}
Else
<p>No Record Found</p>
}

I hope this tutorial 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 Frankfurt - HostForLIFE.eu :: How to Refresh PartialView Automatically?

clock March 5, 2015 07:07 by author Peter

In this post, I will tell you about Refresh PartialView Automatically in ASP.NET MVC 6.  First thing you can do is Create a MVC app on Visual Studio and then add two Classes to your model folder.

using System.ComponentModel.DataAnnotations;
namespace AutoRefresh.Models
{
    public class Employee
    {
        [Key]
        public int Id { get; set; }
        public string Name { get; set; }
        public string ImagePath { get; set; }
    }
}


using System.Data.Entity;
namespace AutoRefresh.Models
{
    public class DemoContext:DbContext
    {
        public DbSet<Employee> employee { get; set; }
    }
}

Now, add a Home Controller and write the following code:
using System;
using System.Linq;
using System.Web.Mvc;
using AutoRefresh.Models;
using System.Web.UI;
namespace AutoRefresh.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            using (DemoContext dbObj = new DemoContext())
            {
               var empList = dbObj.employee.ToList();
                return View(empList);
           }
    }
        [OutputCache(Location = OutputCacheLocation.Client, VaryByParam = "none", Duration = 2)]
        public PartialViewResult _employeeShow()
       {
            using (DemoContext dbObj = new DemoContext())
            {
                var empList = dbObj.employee.ToList();
                int MinId = empList.Min(a => a.Id);
                int MaxId = empList.Max(a => a.Id);
               //generate a random number
                int GetRandomId = new Random().Next(MinId, (MaxId + 1));
                var getRandomemployee=empList.Find(a => a.Id == GetRandomId);
                return PartialView("_employeeShow", getRandomemployee);
            }
        }
     }
}


From the above code, I used OutputCache to get Data from Cache. Next step, add a PartialView _employeeShow to show the Employee.
@model AutoRefresh.Models.Employee
<div class="divEmployee" style="margin-left: 50px;">
    <img src="@Model.ImagePath" width="100" height="100" />
    <span>@Model.Name</span>
</div>

Now , create the Index View. With this view we will load our PartialView.
@model IEnumerable<AutoRefresh.Models.Employee>
@{
    ViewBag.Title = "Index";
}
<script src="~/Scripts/jquery-2.1.1.min.js"></script>
<script type="text/javascript">
    $(document).ready(function () {
        setInterval(function () {
            $('#Employee').load('/Home/_employeeShow')
        },2000);
    });
</script>
<h2>Employee</h2>
<div id="Employee">
    @Html.Partial("_employeeShow", Model.FirstOrDefault())
</div>

Using Jquery, I’m loading the PartialView in every 2 seconds.

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 :: Check Username Availability in ASP.NET MVC with Ajax and jQuery

clock February 27, 2015 06:29 by author Peter

Generally in web application, users got to register to perform some operation. Therefore every user ought to have unique username. during this tutorial we are going to see a way to check Username availability Instantly using Ajax and jQuery. First, let’s create an empty ASP.NET 6 project and then Add model classes to model folder and write the following code:

using System.ComponentModel.DataAnnotations; 
namespace CheckUsernameDemo.Models
{
    public class Employee
   {
        [Key]
        public int Id { get; set; }
        public string Username { get; set; }
        public string Name { get; set; }
        public string Title { get; set; }
    }
}

Add another class
using System.Data.Entity;
namespace CheckUsernameDemo.Models
{
    public class DemoContext:DbContext
    {
        public DbSet<Employee> Employees { get; set; }
    }
}

Next step, Add a HomeController. Then an Index Action to It. Here is the code that I used:
using System.Linq;
using System.Web.Mvc;
using CheckUsernameDemo.Models;
namespace CheckUsernameDemo.Controllers
{
    public class HomeController : Controller
    {
        DemoContext dbObj = new DemoContext();
        public ActionResult Index()
        {  
            return View();
        }
    }
}

Now, make a Index View and write the following code.
@model CheckUsernameDemo.Models.Employee
@{
    ViewBag.Title = "Index";
}  
<h2>Register Here</h2>
@using (Html.BeginForm()) {
    @Html.AntiForgeryToken()
    @Html.ValidationSummary()
    <table>
        <tr>
            <td> @Html.LabelFor(m => m.Username)</td>
            <td>
                @Html.TextBoxFor(m => m.Username)
            </td>
            <td>
                <label id="chkAvailable"></label>
            </td>
        </tr>
        <tr>
            <td> @Html.LabelFor(m => m.Name)</td>
           <td>
                @Html.TextBoxFor(m => m.Name)
            </td>
            <td></td>
        </tr>
        <tr>
            <td> @Html.LabelFor(m => m.Title)</td>
            <td>
                @Html.TextBoxFor(m => m.Title)
            </td>
           <td></td>
        </tr>
        <tr>            
            <td colspan="3">
                <input type="submit" value="Register" class="btnRegister"/>
            </td>
        </tr>
    </table>
}

Now in order to examine Username accessibility Instantly we are going to Ajax call on modification Event of username Textbox. But before writing jquery code we are going to add a method in Home Controller.
public string CheckUsername(string userName)
       {
           string IsAvailable;
           var getData = dbObj.Employees.FirstOrDefault(m => m.Username == userName.Trim());
           if(getData == null)
           {
               IsAvailable = "Available";
           }
           else
           {
               IsAvailable = "Not Available";
           }
           return IsAvailable;
       }

On the above code, we’ll find Employee using EntityFramework query. It will get Employee with that username then method will return Not Available otherwise Available. Now write jQuery code on change event on Username textbox.
<script type="text/javascript">
    $(document).ready(function () {
        $('#Username').on('change', function () {
           var getName = $(this).val();
            $.ajax({
                type: 'POST',
                contentType: 'application/json; charset=utf-8',
                url: 'Home/CheckUsername',
                data: "{ 'userName':' " + getName + "' }",
                success: function (data) {
                    if (data == "Available") {
                        $('#chkAvailable').html('Username Is ' + data);
                        $('#chkAvailable').css('color', 'green'); 
                    } else {
                        $('#chkAvailable').html('Usernam Is ' + data);
                        $('#chkAvailable').css('color', 'red');
                        $('#Username').focus();
                    }
                },
                error: function (data) {
                    alert('Error in Getting Result');
                }
            });
        });
    })
</script>

With that code, we are passing the current Textbox value to Controller method to Check Username Availability. And here is the output:

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 UK - HostForLIFE.eu :: How to use the table to Apply Custom Filter & Pagination with AngularJS in ASP.NET MVC ?

clock February 26, 2015 06:15 by author Peter

In this article I will explain you about How to use the table to apply Custom filter and pagination with angularJS in ASP.NET MVC 6. First step, you must write down the code below to your Index View.

<div>
    <div ng-controller="EmpList">
       Select Number to show items Per Page <select ng-model="PerPageItems">
            <option value="5">5</option>
            <option value="10">10</option>
            <option value="15">15</option>
            <option value="20">20</option>
        </select>
        <div ng-show="filteredItems > 0">
            <table class="table table-striped" id="tblEmp">
                <tr>
                    <th>
                        First Name <a ng-click="orderByField='FirstName';">Sort</a>
                    </th>
                    <th>
                        Last Name <a ng-click="orderByField='LastName';">Sort</a>
                    </th>
                    <th>
                        Title <a ng-click="orderByField='Title';">Sort</a>                    
</th>
                </tr>
                <tr ng-repeat="items in empList | orderBy:orderByField | Pagestart:(currentPage-1)*PerPageItems | limitTo:PerPageItems ">                    
 <td>
                        {{items.FirstName}}
                    </td>
                    <td>
                        {{items.LastName}}
                    </td>
                    <td>
                        {{items.Title}}
                    </td>
                </tr>
            </table>
        </div>
        <div ng-show="filteredItems > 0">
            <pagination page="currentPage" total-items="filteredItems" ng-model="currentPage"  items-per-page="PerPageItems"></pagination>
        </div>
    </div>
</div>


And now, write the below code to your JS file.
var myApp = angular.module('myApp1', ['ui.bootstrap']); 
myApp.filter('Pagestart', function () {    // custom filter
    return function (input, start) {
        if (input) {
            start = +start;
            return input.slice(start);
        }
        return [];
    }
}); 
myApp.controller('EmpList', function ($scope, $http, $timeout) {
    var EmployeesJson = $http.get("/Home/GetEmployees");
    $scope.orderByField = 'FirstName';
    EmployeesJson.success(function (data) {
        $scope.empList = data;
        $scope.filteredItems = $scope.empList.length;  
        $scope.totalItems = $scope.empList.length;  // Total number of item in list.
        $scope.PerPageItems = 5;  // Intially Set 5 Items to display on page.
        $scope.currentPage = 1;   // Set the Intial currnet page
    });
    $scope.filter = function () {
        $timeout(function () {
            $scope.filteredItems = $scope.filtered.length;
        }, 10);
    };
});

Now, write the following JS Library to your View. And then, run the project. I hope this tutorial 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 Russia - HostForLIFE.eu :: How to Highlight Selected Menu Item in ASP.NET MVC ?

clock February 13, 2015 07:23 by author Peter

Each time we are making application with some quite menu it's nice to own the essential practicality to focus on selected menu item in ASP.NET MVC 6 . There are some solutions you'll notice within the web, but when I've tried to use one it hasn't been operating excellent. So, let's produce our own in 3 steps.

1. First of all we want to make MVC HTML helper class, containing method to use the appropriate CSS class based on some conditions.
2. Now, we want the CSS class itself to be applied for selected  menu item, it is very easy, background color change, font modification, etc.
3. The menu HTML ought to be changed to use our helper while rendering page.

And here is the example helper class code:
public static class MenuHelper
{
    public static string IsSelected(this HtmlHelper html, string controller = null, string action = null)
    {
        const string cssClass = "selected";
        string currentAction = (string)html.ViewContext.RouteData.Values["action"];
        string currentController = (string)html.ViewContext.RouteData.Values["controller"];
        if (String.IsNullOrEmpty(controller))
            controller = currentController;
        if (String.IsNullOrEmpty(action))
            action = currentAction;
        return controller.Split(';').Contains(currentController) && action.Split(';').Contains(currentAction) ?
            cssClass : String.Empty;
   }
}

Pretty easy, isn't it? we are setting the 'selected" CSS class based on the controller and action combination (both arguments are optional). sometimes we've in the menu only main pages, however we would like to tell user in a way regarding the context whereas he's opening sub-page. the best way is to stay the menu item highlighted when user is browsing some sub-pages. This helper implementation is supporting this case likewise. we are able to pass as arguments many controller names, or action names and for those groups we are able to highlight particular menu item.

Highlight menu item for Index action from Home controller:
class="@Html.IsSelected(null, "Index")"

Highlight menu item for several actions coming from one controller:
class="@Html.IsSelected(null, "Contact;About")"

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 UK - HostForLIFE.eu :: How to create a DropDownList field for ASP.NET MVC Razor view ?

clock February 12, 2015 07:13 by author Peter

Today, this tutorial will show you how to create a DropDownList field for ASP.NET MVC 6 Razor view. First, you must create a new project and here is the code that I use:

Controller
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcNew.Models;
namespace MvcNew.Controllers
{
    public class HomeController : Controller
    {
            public ActionResult DropDown()
        {
            List<SelectListItem> items = new List<SelectListItem>();
            items.Add(new SelectListItem { Text = "Developer", Value = "0" });
            items.Add(new SelectListItem { Text = "Analyst", Value = "1" });
            items.Add(new SelectListItem { Text = "Admin", Value = "2", Selected = true });
            items.Add(new SelectListItem { Text = "Manager", Value = "3" });
            ViewBag.Desig_Type = items;
            return View();     
        }
    }
}

View
@model MvcNew.Models.Home
@{
    ViewBag.Title = "Drop";
}
<h2>Drop</h2>
   @using (Html.BeginForm("Category", "Home", FormMethod.Get)) {
    <fieldset>
            Designation
            @Html.DropDownList("Desig_Type")
        <p>
            <input type="submit" value="Submit" />
        </p>
    </fieldset>
}
<div>
    @Html.ActionLink("Back to List", "Index")
</div>
@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}
And here is the output from the above code:

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 Europe - HostForLIFE.eu :: How to Create a Gridview Header Check Box in ASP.NET MVC ?

clock February 6, 2015 06:53 by author Peter

In this article we will tell you How to Create Header Checkbox in web Gridview with ASP.NET MVC 6. You need to Simply Change in this Example is that in Index.cshtml document.

I used the following code to show the Header Checkbox:
columns: grid.Columns(
        grid.Column(header: "{CheckBoxHeading}",  format:
            @<text><input class="box"  type="checkbox" /></text>),
            grid.Column("ID", canSort: true, style: "Id"),
        grid.Column("Name", canSort: true, style: "Name"),
        grid.Column("Question", canSort: true, style: "Question"),
         grid.Column("", header: "Actions", format: @<text>
                 @Html.ActionLink("Edit",   "Edit",   new { id=item.Id} )
                  @Html.ActionLink("Delete", "Delete", new { id=item.Id} )
                </text>
      )
).ToString().Replace("{CheckBoxHeading}", "<input type='checkbox' id='allBox'/>")  


In which we additionally give Facility to user to choose multiple record at once focused around checkbox selection. When client click on Header checkbox then it will automatically check all the checkbox means select All row or record.

if the GridView contain large number of Record at that point user wish to delete all record then user have needed more time to pick each {and every|and every} record by click on each row checkbox, thus for that reason we offer a facility to user simply click on one Header CheckBox and choose the all row or Record in Gridview.

If you have previous Example, then simply copy this code and paste it in Index.CSHtml file:
Index.CSHtml File
@model IEnumerable<finalpaging.Models.poll>
@{
    ViewBag.Title = "Index";
}
<!DOCTYPE html>
<html>
<head>
    <title>WebgridSample</title>
    <script src="../../Scripts/jquery-1.7.1.min.js" type="text/javascript"></script>
    <script type="text/javascript">
     //Select or Deselect all checkboxs in the grid       
$(document).ready(function () {
            $("#allBox").click(function () {
                $(".box").attr("checked", $(this).attr("checked") ? true : false);
            });
                           });
</script>
    <style type="text/css">
        .webGrid { margin: 4px; border-collapse: collapse; width: 500px;  background-color:#FCFCFC;}        .header { background-color: #C1D4E6; font-weight: bold; color: #FFF; }
        .webGrid th, .webGrid td { border: 1px solid #C0C0C0; padding: 5px; }
        .alt { background-color: #E4E9F5; color: #000; }
        .gridHead a:hover {text-decoration:underline;}
        .description { width:auto}
        .select{background-color: #389DF5}
    </style>
</head>
<body>
    <p>
    @Html.ActionLink("Create New", "Create")
</p>
    @{
    finalpaging.Models.poll product = new finalpaging.Models.poll();
}
    @{
    var grid = new WebGrid(Model, canPage: true, rowsPerPage: 10, selectionFieldName: "selectedRow",ajaxUpdateContainerId: "gridContent");
        grid.Pager(WebGridPagerModes.NextPrevious);}
        <div id="gridContent">                  
MvcHtmlString.Create(grid.GetHtml(tableStyle: "webGrid",
                headerStyle: "header",
                alternatingRowStyle: "alt",
                selectedRowStyle: "select",
    fillEmptyRows: false,    
    footerStyle: "footer",
    mode: WebGridPagerModes.All,
    firstText: "<< First",
    previousText: "< Prev",
    nextText: "Next >",
    lastText: "Last >>",
    columns: grid.Columns(
        grid.Column(header: "{CheckBoxHeading}",  format:
            @<text><input class="box"  type="checkbox" /></text>),
            grid.Column("ID", canSort: true, style: "Id"),
        grid.Column("Name", canSort: true, style: "Name"),
        grid.Column("Question", canSort: true, style: "Question"),
         grid.Column("", header: "Actions", format: @<text>
                 @Html.ActionLink("Edit",   "Edit",   new { id=item.Id} )
                  @Html.ActionLink("Delete", "Delete", new { id=item.Id} )
                </text>
      )
)).ToString().Replace("{CheckBoxHeading}", "<input type='checkbox' id='allBox'/>")                            
),
 </div>   
</body>
</html>

I hope this tutorial 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 Belgium - HostForLIFE.eu :: How to Handling multiple submit buttons on the same form in MVC ?

clock February 5, 2015 07:08 by author Peter

Sometimes you got situation like more than one submit buttons on a similar form in ASP.NET MVC 6. At that point, How we will handle the click event of every and each buttons on your form?

In this post I will explain you about Handling multiple submit buttons on the same form in MVC.To fix this problem, I'm progressing to justify the varied techniques for handling multiple buttons on the same form in MVC. Suppose you've got a user Login form like as below:

On the above picture, we have the SignUp, SignIn and the Cancel buttons. Suppose on Signup button click you have to open Signup window & on SignIn button click you have to open Login window and on Cancel button click you are returning to home page. For handling all of the above buttons, we have the following methods:
Export Gridview to Excel: Gridview to Excel
Insert,Update,Delete in ModalPopup CRUD operation in ModalPopup
Read and Write in Text File in ASP.NET Read and Write File in ASP.NET

Now, Make the view Form with Multiple Button in Home Folder with the following code.

MultipleCommand.cshtml
@model  Mvc4_Multiple_Submit_Button.Models.RegistrationModel
@{
    ViewBag.Title = "Handling Multiple Command Buttons";
}
<script src="../../Scripts/jquery-1.7.1.min.js" type="text/javascript"></script>
<script src="../../Scripts/jquery.validate.min.js" type="text/javascript"></script>
<script src="../../Scripts/jquery.validate.unobtrusive.min.js" type="text/javascript"></script>
<h2>User's Signup Form</h2>
@using (Html.BeginForm("MultipleCommand", "Home", FormMethod.Post, new { id = "submitForm" }))
{
    <fieldset>
        <legend>Registration Form</legend>
        <ol>
            <li>
                @Html.LabelFor(m => m.Name)
                @Html.TextBoxFor(m => m.Name, new { maxlength = 50 })
                @Html.ValidationMessageFor(m => m.Name)
            </li>
            <li>
                @Html.LabelFor(m => m.Address)
                @Html.TextAreaFor(m => m.Address, new { maxlength = 200 })
                @Html.ValidationMessageFor(m => m.Address)
            </li>
            <li>
                @Html.LabelFor(m => m.MobileNo)
                @Html.TextBoxFor(m => m.MobileNo, new { maxlength = 10 })
                @Html.ValidationMessageFor(m => m.MobileNo)
            </li>
        </ol>
        <button type="submit" id="btnSave" name="Command" value="Save">
            Save</button>
        <button type="submit" id="btnSubmit" name="Command" value="Submit">
            Submit</button>
        <button  type="submit" id="btnCancel" name="Command"  value="Cancel" onclick="$('#submitForm').submit()">
            Cancel (Server Side)</button>
        <button  type="submit" id="btnCancelSecForm" name="Command"  value="Cancel" onclick="$('#cancelForm').submit()">
            Cancel (Server Side by Second Form)</button>
        <button name="ClientCancel" type="button" onclick=" document.location.href = $('#cancelUrl').attr('href');">
            Cancel (Client Side)</button>
        <a id="cancelUrl" href="@Html.AttributeEncode(Url.Action("Index", "Home"))" style="display:none;">
        </a>
    </fieldset>
}
@using (Html.BeginForm("MultipleButtonCancel", "Home", FormMethod.Post, new { id = "cancelForm" })) { }

Next step, in Homecontroller include the MultipleCommand Method to handle the multiple button with the following code.
HomeController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Mvc4_Multiple_Submit_Button.Models;
namespace Mvc4_Multiple_Submit_Button.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }
              public ActionResult MultipleCommand()
        {
            return View();
        }
        [HttpPost]
        public ActionResult MultipleCommand(RegistrationModel mReg, string Command)
        {
            if (Command == "Save")
            {
                //TO DO : for Save button Click
            }
            else if (Command == "Submit")
            {
                //TO DO : for Submit button Click
            }
            else
            {
                //TO DO : for Cancel button Click
                return RedirectToAction("Index");
            }
            return View();
        }
        [HttpPost]
        public ActionResult MultipleButtonCancel()
        {
            //TO DO : for Cancel button Click
            return RedirectToAction("Index");
        }
    }
}

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