Sunday, August 3, 2014

Parent and Child dependent dropdown list using MVC

My objective is to dependent drop down list.

Output:



















Step1: Please have a look below view code

@model ContosoUniversity.Models.Enrollment

@{
    ViewBag.Title = "Create";
}

<script src="../../Scripts/jquery-1.7.1.js" type="text/javascript"></script>
<script src="../../Scripts/jquery-1.7.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
    $(document).ready(function () {
        //Dropdownlist Selectedchange event
        $("#Countries").change(function () {
            $("#State").empty();
            $.ajax({
                type: 'POST',
                url: '@Url.Action("GetStates")', // we are calling json method
                dataType: 'json',
                data: { id: $("#Countries").val() },
               // here we are get value of selected country and passing same value as inputto json method GetStates.
                success: function (states) {
                    // states contains the JSON formatted list
                    // of states passed from the controller
                    $.each(states, function (i, state) {
                    $("#State").append('<option value="' + state.Value + '">' +  state.Text + '</option>');                                                                                                
                    // here we are adding option for States
                    });
                },
                error: function (ex) {
                    alert('Failed to retrieve states.' + ex);
                }
            });
            return false;
        })
    });

</script>

<script type="text/javascript">
    $(document).ready(function () {
        //Dropdownlist Selectedchange event
        $("#State").change(function () {
            $("#city").empty();
            $.ajax({
                type: 'POST',
                url: '@Url.Action("GetCity")',
                dataType: 'json',
                data: { id: $("#State").val() },
                success: function (citys) {
                    // states contains the JSON formatted list
                    // of states passed from the controller
                    $.each(citys, function (i, city) {
                        $("#city").append('<option value="'+ city.Value + '">'+ city.Text + '</option>');
                    });
                },

                error: function (ex) {

                    alert('Failed to retrieve states.' + ex);

                }

            });

            return false;

        })

    });

</script> 

@Scripts.Render("~/bundles/jqueryui")
<script >
    $(function () {
        $("#datepicker").datepicker();
    });
</script>

<h2>Create</h2>

@using (Html.BeginForm()) {
    @Html.ValidationSummary(true)

    
    
    
    <fieldset>
        <legend>Enrollment</legend>

        <div class="editor-label">
            @Html.LabelFor(model => model.CourseID, "Course")
        </div>
        <div class="editor-field">
            @Html.DropDownList("CourseID", String.Empty)
            @Html.ValidationMessageFor(model => model.CourseID)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.StudentID, "Student")
        </div>
        <div class="editor-field">
            @Html.DropDownList("StudentID", String.Empty)
            @Html.ValidationMessageFor(model => model.StudentID)
        </div>
        <div class="editor-label">
            @Html.LabelFor(model => model.Grade)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Grade)
            @Html.ValidationMessageFor(model => model.Grade)
        </div>

        <div>
            @Html.DropDownList("Countries", ViewData["country"] as List<SelectListItem>)
        </div>
        
        <div>
            @Html.DropDownList("State", new SelectList(string.Empty, "Value", "Text"), "Please select a State", new { style = "width:250px", @class = "d1" })
        </div>

        <div>
            @Html.DropDownList("city", new SelectList(string.Empty, "Value", "Text"), "Please select a city", new { style = "width:250px", @class = "d1" })
        </div>

        
        
        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}


Step2: have a look controller.


using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ContosoUniversity.Models;
using ContosoUniversity.DAL;

namespace ContosoUniversity.Controllers
{
    public class EnrollmentController : Controller
    {
        private SchoolContext db = new SchoolContext();

        //
        // GET: /Enrollment/

        public ActionResult Index(int? page)
        {
            var enrollments = db.Enrollments.Include(e => e.Course).Include(e => e.Student);
            return View(enrollments.ToList());
        }

        //
        // GET: /Enrollment/Details/5

        public ActionResult Details(int id = 0)
        {
            Enrollment enrollment = db.Enrollments.Find(id);
            if (enrollment == null)
            {
                return HttpNotFound();
            }
            return View(enrollment);
        }

        //
        // GET: /Enrollment/Create

        public ActionResult Create()
        {
            ViewBag.CourseID = new SelectList(db.Courses, "CourseID", "Title");
            ViewBag.StudentID = new SelectList(db.Students, "StudentID", "LastName");

            List<SelectListItem> li = new List<SelectListItem>();
            li.Add(new SelectListItem { Text = "Select", Value = "0" });
            li.Add(new SelectListItem { Text = "Bangladesh", Value = "1" });
            li.Add(new SelectListItem { Text = "Srilanka", Value = "2" });
            li.Add(new SelectListItem { Text = "China", Value = "3" });
            li.Add(new SelectListItem { Text = "Austrila", Value = "4" });
            li.Add(new SelectListItem { Text = "USA", Value = "5" });
            li.Add(new SelectListItem { Text = "UK", Value = "6" });
            ViewData["country"] = li;


            return View();
        }

        //
        // POST: /Enrollment/Create

        [HttpPost]
        public ActionResult Create(Enrollment enrollment)
        {
            if (ModelState.IsValid)
            {
                db.Enrollments.Add(enrollment);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            ViewBag.CourseID = new SelectList(db.Courses, "CourseID", "Title", enrollment.CourseID);
            ViewBag.StudentID = new SelectList(db.Students, "StudentID", "LastName", enrollment.StudentID);



            return View(enrollment);
        }

        //
        // GET: /Enrollment/Edit/5

        public ActionResult Edit(int id = 0)
        {
            Enrollment enrollment = db.Enrollments.Find(id);
            if (enrollment == null)
            {
                return HttpNotFound();
            }
            ViewBag.CourseID = new SelectList(db.Courses, "CourseID", "Title", enrollment.CourseID);
            ViewBag.StudentID = new SelectList(db.Students, "StudentID", "LastName", enrollment.StudentID);
            return View(enrollment);
        }

        //
        // POST: /Enrollment/Edit/5

        [HttpPost]
        public ActionResult Edit(Enrollment enrollment)
        {
            if (ModelState.IsValid)
            {
                db.Entry(enrollment).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            ViewBag.CourseID = new SelectList(db.Courses, "CourseID", "Title", enrollment.CourseID);
            ViewBag.StudentID = new SelectList(db.Students, "StudentID", "LastName", enrollment.StudentID);
            return View(enrollment);
        }

        //
        // GET: /Enrollment/Delete/5

        public ActionResult Delete(int id = 0)
        {
            Enrollment enrollment = db.Enrollments.Find(id);
            if (enrollment == null)
            {
                return HttpNotFound();
            }
            return View(enrollment);
        }

        public ActionResult getCourseId(string course)
        {
            return View(course);
        }

        //
        // POST: /Enrollment/Delete/5

        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(int id)
        {
            Enrollment enrollment = db.Enrollments.Find(id);
            db.Enrollments.Remove(enrollment);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }

        public JsonResult GetStates(string id)
        {
            List<SelectListItem> states = new List<SelectListItem>();
            switch (id)
            {
                case "1":
                    states.Add(new SelectListItem { Text = "Select", Value = "0" });
                    states.Add(new SelectListItem { Text = "Dhaka", Value = "1" });
                    states.Add(new SelectListItem { Text = "Khulna", Value = "2" });
                    states.Add(new SelectListItem { Text = "Borishal", Value = "3" });
                    states.Add(new SelectListItem { Text = "Chittagong", Value = "4" });
                    states.Add(new SelectListItem { Text = "Syllet", Value = "5" });
                    break;
                case "UK":
                    break;
                case "India":
                    break;
            }

            return Json(new SelectList(states, "Value", "Text"));

        }

        public JsonResult GetCity(string id)
        {
            List<SelectListItem> City = new List<SelectListItem>();
            switch (id)
            {
                case "1":
                    City.Add(new SelectListItem { Text = "Select", Value = "0" });
                    City.Add(new SelectListItem { Text = "Gazipur", Value = "1" });
                    City.Add(new SelectListItem { Text = "Gopalgong", Value = "2" });

                    break;
            }
            return Json(new SelectList(City, "Value", "Text"));
        }
    }

}

Step3: then you will get above output

WebGrid Example using MVC

My objective is to add WebGrid pagination in MVC webapps.
Expected output:




















Step1: First add WebGrid plugin in your project. 

For adding go to tools >> Library Package Manager >> NutGut package for solution >> search by WebGrid and then install.

Step2: Open your views and add below code.

@model IEnumerable<ContosoUniversity.Models.Course>

@{
    ViewBag.Title = "Course";
}

<h2>Course</h2>

<p>
    @Html.ActionLink("Create New", "Create")
</p>

<h2>
    Course Details
</h2>

@{
var grid = new WebGrid(source: Model, rowsPerPage: 5, canPage: true, canSort: true);
@grid.GetHtml(columns:grid.Columns(  
grid.Column(columnName:"Title", header:"Title"),
grid.Column(columnName: "Credits", header: "Credits"),
grid.Column(format: (item) => Html.ActionLink("Edit", "Edit", new { id = item.CourseID} )),
grid.Column(format: (item) => Html.ActionLink("Details", "Details", new { id = item.CourseID })),
grid.Column(format: (item) => Html.ActionLink("Delete", "Delete", new { id = item.CourseID }))
)
)
}

Step3: Open your controller and add below code.

private SchoolContext db = new SchoolContext();

        //
        // GET: /Course/

        public ActionResult Index(int? page)
        {
            return View(db.Courses.ToList());
        }

Step4: Now run your application and then you will get above output. 

Let me know if you have any issues.


Thursday, July 3, 2014

Multiple Pagination using Grails

How to multiple pagination in Grails


Step1: In GSP


<!doctype html>
<html>
    <head>
        <meta name="layout" content="main">
        <g:set var="entityName" value="${message(code: 'employees.label', default: 'Employees')}" />
        <title><g:message code="default.list.label" args="[entityName]" /></title>
       
        <style>
table, td, th {
    border: 1px solid green;
    padding: 1px;
    font-size:88%;
}

th {
    background-color: green;
    color: white;
    padding: 1px;
    font-size:85%;
}
</style>
       
    </head>
    <body>   
    <h1>Welcome to Dashboard</h1>
        <g:if test="${employeesInstanceList}">
        <div class="box2">       
        <h1>Employee List</h1>
            <table>
                <thead>
                    <tr>
                   
                        <g:sortableColumn property="firstName" title="${message(code: 'employees.firstName.label', default: 'First Name')}" />
                   
                        <g:sortableColumn property="lastName" title="${message(code: 'employees.lastName.label', default: 'Last Name')}" />
                   
                        <g:sortableColumn property="dateOfbirth" title="${message(code: 'employees.dateOfbirth.label', default: 'Date Ofbirth')}" />                   
                   
                    </tr>
                </thead>
                <tbody>
                <g:each in="${employeesInstanceList}" status="i" var="employeesInstance">
                    <tr class="${(i % 2) == 0 ? 'even' : 'odd'}">
                   
                        <td><g:link action="show" id="${employeesInstance.id}">${fieldValue(bean: employeesInstance, field: "firstName")}</g:link></td>
                   
                        <td>${fieldValue(bean: employeesInstance, field: "lastName")}</td>
                   
                        <td><g:formatDate date="${employeesInstance.dateOfbirth}" /></td>
                                       
                    </tr>
                </g:each>
                </tbody>
            </table>
            <div class="pagination">               
                <g:paginate total="${employeesInstanceTotal}" max="5" offset="${session.empPagination?.offset}" params="${[paginate:'Employee']}"/>
            </div>
        </div>
        </g:if>
       
       
        <g:if test="${payrollInstanceList}">
        <div class="box1">
        <h1>Payroll List</h1>
            <table>
                <thead>
                    <tr>
                                       
                        <g:sortableColumn property="payDate" title="${message(code: 'payroll.payDate.label', default: 'Employeess')}" />
                       
                        <g:sortableColumn property="payDate" title="${message(code: 'payroll.payDate.label', default: 'Components')}" />
                   
                        <g:sortableColumn property="payDate" title="${message(code: 'payroll.payDate.label', default: 'Pay Date')}" />
                   
                        <g:sortableColumn property="allowanceAmt" title="${message(code: 'payroll.allowanceAmt.label', default: 'Allowance')}" />
                   
                        <g:sortableColumn property="deductionAmt" title="${message(code: 'payroll.deductionAmt.label', default: 'Deduction')}" />
                       
                        <g:sortableColumn property="deductionAmt" title="${message(code: 'payroll.deductionAmt.label', default: 'Companys')}" />                                                               
                   
                    </tr>
                </thead>
                <tbody>
                <g:each in="${payrollInstanceList}" status="i" var="payrollInstance">
                    <tr class="${(i % 2) == 0 ? 'even' : 'odd'}">
                   
                        <td><g:link action="show" id="${payrollInstance.id}">${fieldValue(bean: payrollInstance, field: "employeess")}</g:link></td>
                   
                        <td>${fieldValue(bean: payrollInstance, field: "allowanceTypes")}</td>                                           
                                                                                   
                        <td><g:formatDate date="${payrollInstance.payDate}" /></td>
                   
                        <td>${fieldValue(bean: payrollInstance, field: "allowanceAmt")}</td>
                   
                        <td>${fieldValue(bean: payrollInstance, field: "deductionAmt")}</td>
                       
                        <td>${fieldValue(bean: payrollInstance, field: "companys")}</td>
                   
                    </tr>
                </g:each>
                </tbody>
            </table>
            <div class="pagination">
            <g:paginate total="${payrollInstanceTotal}" max="5" offset="${session.payPagination?.offset}" params="${[paginate:'Payroll']}"/>
            </div>
        </div>
        </g:if>
    </body>
</html>



Step2: In controller


class IndexController {
    def index() {  // index is the default action for any controller
        redirect(action:"list")
    }
   
    def list() {
       
        if (params.paginate == 'Employee') {
            def empPagination = [max: params.max, offset: params.offset]
            session.empPagination = empPagination
          } else if (params.paginate == 'Payroll') {
            def payPagination = [max: params.max, offset: params.offset]
            session.payPagination = payPagination   
          }
          def empList = Employees.list(session.empPagination ?: [max: 5, offset: 0])
          def payList = Payroll.list(session.payPagination ?: [max: 5, offset: 0])

          params.offset = null
          params.max = null
          [employeesInstanceList: empList, employeesInstanceTotal: Employees.count(), payrollInstanceList: payList, payrollInstanceTotal: Payroll.count()]
        }  

    }





Friday, June 27, 2014

Parent and Child list check in groovy and grails

My objective is to ensure parent child list check using groovy and grails

 

 Step1: write ajax code in your gsp view page 


<html>
    <head>
        <meta name="layout" content="main">
        <g:set var="entityName" value="${message(code: 'WFLayer.label', default: 'WFLayer')}" />
        <g:javascript library="prototype"/> 
              
       
        <g:javascript>
            document.observe('dom:loaded', function() {
                $("master").observe("change", respondToSelect);
            });

           
            function respondToSelect(event)
            {
               new Ajax.Updater("sub", "/ADHRPAY/WFLayer/getDate",
                                {
                                method:'get', parameters: 
                                {
                                selectedValue : $F("master")
                                }, onSuccess: function(transport)
                                {
                                   
                                     setTimeout(initializeSub,1000);   
                                }
                                }
                                );
                                                  
            }                                                                                  
        </g:javascript>

       
        <title><g:message code="default.create.label" args="[entityName]" /></title>           
    </head>


in above code /ADHRPAY/WFLayer/getDate. is called /ProjectName/ControllerName/method


Step2: write method code in your groovy class

def getDate() {
               def result
        def sqlConnect = new Sql(dataSource)
        if(params.selectedValue=='Department'){
            result = sqlConnect.rows("select department_name as name from departments")
        }
        else if(params.selectedValue=='Section'){
            result = sqlConnect.rows("select section_name as name from sections")
        }
        else if(params.selectedValue == "Employee"){
            result = sqlConnect.rows("select concat(first_name,' ',last_name) as name from employees")
        }
        render(template:'getListValue',model:[selectResult:result])
       
    }
   



Step3: write template code in your template gsp view

<g:select name="sub" value="" from="${selectResult.name}"></g:select>


Step4: Finally change your gsp page from which you are sending value to your controller using Ajax support.

<div class="fieldcontain ${hasErrors(bean: WFLayerInstance, field: 'layerType', 'error')} ">
    <label for="layerType">
        <g:message code="WFLayer.layerType.label" default="Layer Type" />
       
    </label>
    <%-- <g:select id="master" name="master" from="${WFLayerInstance.constraints.layerType.inList}" value="${WFLayerInstance?.layerType}" valueMessagePrefix="WFLayer.layerType" noSelection="['': '']"/> --%>
    <g:select id="master" from="${WFLayerInstance.constraints.layerType.inList}" name="master" />
</div>

<div class="fieldcontain ${hasErrors(bean: WFLayerInstance, field: 'layerId', 'error')} required">
    <label for="layerId">
        <g:message code="WFLayer.layerId.label" default="Layer Name" />
    </label>
    <g:select id="sub" name="sub" from="" value="${WFLayerInstance.layerId}"/>
</div>



Best way to keep your all GSP file in same folder.

Step5: Now run your application and then you will get below output(once your select layer type then layer name will be displayed).