Skip to main content

MVC4 sample Application

                                          MVC 4 sample Webgrid Application With JQuery Ajax

1. Introduction 
MVC is not a new concept made for ASP.NET. Even iOS framework is based on MVC for its development.
MVC is a general concept of Software Engineering. 
The central idea behind MVC is separation of concerns and code reusability. Views do not need to know where the data come from. Models also do not know anything about how the data will be displayed. By doing so, you can have very flexible architecture that can be changed and maintained easily. 
This booklet explains the followings:
 MVC Overview
 Controllers
 Views (WebForms and Razor)
 Models and Validations
 Filters
 Unobtrusive Ajax
 Dependency Injection (DI) Pattern 
The following tools are used for the project:
 Visual Studio Express 2012 for Web
 SQL Server 2012 Express

2. ASP.NET MVC 
Ok, everybody talks about MVC and you know what MVC stands for. 
 M (Model): Data objects – business logic, validation, and DB access
 V (View) : UI
 C (Controller): well, it does many things; handles user interaction, works with models, and selects a view, etc. 
In this chapter, we look at how MVC handles a request (execution process) first. It will give you the high level view of what MVC is. And then let’s find out how MVC project looks like from the developer’s point of view. 


so lets start with a sample application here i have provided sample codes for controller,Models and views
controller
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using projectManagement.Models;
namespace projectManagement.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/
          
            List<Projects> emp=new List<Projects>()
            {
            new Projects () { ID=100,projectName="Geojith",employeeName="Jithin"},
            new Projects () { ID=101,projectName="CateringManagement",employeeName="Jerin"},
          
            };
           

        public ActionResult Index()
        {
            List<Projects> emplist = new List<Projects>();
          
            return View(emp);
        }
        public ActionResult update()
        {
            string message = "Success";
            return Json(message, JsonRequestBehavior.AllowGet);
        }
       
        public ActionResult updatebyajax()
        {
           
            return View(emp);
        }
        [HttpPost]
        public ActionResult Insert(Projects pro)
        {
        
            emp.Add(pro);
          
           
            //return this.Json(new { msg = "success" });
            return View("updatebyajax", emp);
          
        }
    }
}

Views

    Home/updatebyajax
             @model List<projectManagement.Models.Projects>
 <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<link href="../../Content/style.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" >
    $(document).ready(function () {

        $('.edit').hide();
        $('.Insert').hide(); //hiding three buttons initially
        $('.edit-user, .cancel-user').on('click', function () {//common for both editing and cancel ...while cliccking
            var tr = $(this).parents('tr:first'); //it will find the parent table row in which click has occured
            tr.find('.edit, .view').toggle(); //and toggle corresponding edit or view controls
        });

        $('.save-user').on('click', function () {//on clicking save button
            var tr = $(this).parents('tr:first');
            var FirstName = tr.find("#projectName").val(); ///
            var LastName = tr.find("#employeeName").val();
            var UserID = tr.find("#UserID").html();
            tr.find("#lblprojectName").text(FirstName);
            tr.find("#lblemployeeName").text(LastName);
            tr.find('.edit, .view').toggle();
            var UserModel =
            {
                "ID": UserID,
                "FirstName": FirstName,
                "LastName": LastName
            };
            $.ajax({
                url: '/Home/update/',
                data: JSON.stringify(UserModel),
                type: 'POST',
                contentType: 'application/json; charset=utf-8',
                success: function (data) {
                    alert(data);
                }
            });

        });
        $('.delete-user').on('click', function () {//on clicking save button
            alert("Do you Really want to Delete This ?")
            var tr = $(this).parents('tr:first');
            $(this).closest('tr').remove();
        });
        $('.insert-user').on('click', function () {

            $('.insert-user').hide();

            $('p').append('<table>' + '<tr>' + '<td><input type="text" id="UserIDInsert"  class="insert" />' +
                    '<td><input type="text" id="projectNameInsert" class="insert"  />' +
                   '<td><input type="text" id="employeeNameInsert" class="insert" />' + '<td><input type="submit" id="submit" class="insert" /></td>' + '</tr>' + '</table>');
            $('#submit').on('click', function () {
                var tr = $(this).parents('tr:first');
                var projectName = tr.find("#projectNameInsert").val();
                var employeeName = tr.find("#employeeNameInsert").val();
                var UserID = tr.find("#UserIDInsert").val();

                var UserModel =
            {
                "ID": UserID,
                "projectName": projectName,
                "employeeName": employeeName
            };
                $('.insert').hide();
                $.ajax({
                    url: '/Home/Insert/',
                    data: JSON.stringify(UserModel),
                    type: 'POST',
                    contentType: 'application/json; charset=utf-8',
                    success: function () {
                        alert("Value Inserted");
                    }
                });


            })

        });
    }) 

  
</script>

<h2>Student</h2>
@{ 
  
    var grid = new WebGrid(source:Model);
}

<h2>updatebyajax</h2>
<div  id="gridContent" style=" padding:20px; " >
@grid.GetHtml(
       
        selectedRowStyle: "webgrid-selected-row",
        rowStyle: "webgrid-row-style",
            mode: WebGridPagerModes.All,
        columns:
            grid.Columns(
             grid.Column("ID", format: @<text>  <span  class="view">@item.ID </span> <label id="UserID" class="edit">@item.ID</label>  </text>, style: "col1Width" ),
             grid.Column("projectName", "Project Name", format: @<text>  <span  class="view"> <label id="lblprojectName"  >@item.projectName</label> </span> <input type="text" id="projectName" value="@item.projectName" class="edit" />  </text>, style: "col2Width"),
             grid.Column("employeeName", "Employee Name", format: @<text> <span  class="view"> <label id="lblemployeeName">@item.employeeName</label> </span>  <input type="text" id="employeeName" value="@item.employeeName" class="edit" />   </text>, style: "col2Width"),
             grid.Column("Action", format: @<text>
                                <button class="edit-user view" >Edit</button>
                                <button class="delete-user view" >Delete</button>
                               
                                <button class="save-user edit"  >Save</button>
                                <button class="cancel-user edit" >Cancel</button>
                            </text>,  style: "col3Width" , canSort: false)))
          
           <button class="insert-user" >Insert New</button>
         <p> </p>
           </div>

Models

     using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.ComponentModel.DataAnnotations;

namespace projectManagement.Models
{
    public class Projects
    {
        [Key]
        public int ID { get; set; }
        public string projectName { get; set; }
        [DataType(DataType.Date)]
        [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
        public DateTime startdate { get; set; }
        [DataType(DataType.Date)]
        [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
        public DateTime endDate { get; set; }
        public string employeeName { get; set; }
        [RegularExpression(@"^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$",
        ErrorMessage = "Invalid email address.")]
        public string Email { get; set; }

    }

}

Comments

Popular posts from this blog

NHibernate QueryOver Class And Projection....

Introduction The ICriteria API is NHibernate's implementation of Query Object . NHibernate 3.0 introduces the QueryOver api, which combines the use of Extension Methods and Lambda Expressions (both new in .Net 3.5) to provide a statically typesafe wrapper round the ICriteria API. QueryOver uses Lambda Expressions to provide some extra syntax to remove the 'magic strings' from your ICriteria queries. So, for example: .Add(Expression.Eq("Name", "Smith")) becomes: .Where<Person>(p => p.Name == "Smith") With this kind of syntax there are no 'magic strings', and refactoring tools like 'Find All References', and 'Refactor->Rename' work perfectly. Note: QueryOver is intended to remove the references to 'magic strings' from the ICriteria API while maintaining it's opaqueness. It is not a LINQ provider; NHibernate 3.0 has a built-in

Passing Data from View to Controller Using Ajax Example Jquery

Jquery       $ ( '#btnSaveComments' ). click ( function () { var comments = $ ( '#txtComments' ). val (); var selectedId = $ ( '#hdnSelectedId' ). val (); $ . ajax ({ url : '<%: Url.Action("SaveComments")%>' , data : { 'id' : selectedId , 'comments' : comments }, type : "post" , cache : false , success : function ( savingStatus ) { $ ( "#hdnOrigComments" ). val ( $ ( '#txtComments' ). val ()); $ ( '#lblCommentsNotification' ). text ( savingStatus ); }, error : function ( xhr , ajaxOptions , thrownError ) { $ ( '#lblCommentsNotification' ). text ( "Error encountered while saving the comments." ); } }); });     Controller    [ HttpPost ] public ActionResult SaveComments ( int id , string com

The Core Concepts of Angular -- Jithin CJ

I started to learn angular from 2016, I was very curious about the celibacy of this super hero. From my initial understanding is like, the power of angular is only limited on " html decoration "  But this JavaScript framework has the potential to re-define conventional html-css patterns . Modern browsers support for things like modules, classes, lambdas, generators, etc. These features fundamentally transform the JavaScript programming experience. But big changes aren't constrained merely to JavaScript. Web Components are on the horizon. The term Web Components usually refers to a collection of four related W3C specifications: Custom Elements - Enables the extension of HTML through custom tags.  HTML Imports - Enables packaging of various resources (HTML, CSS, JS, etc.).  Template Element - Enables the inclusion of inert HTML in a document.  Shadow DOM - Enables encapsulation of DOM and CSS.  Developers can create fully encapsulated (Shadow DOM) declar