Showing posts with label MVC3. Show all posts
Showing posts with label MVC3. Show all posts

Friday, October 26, 2012

MVC -SelectedList

Today we will see a small example of how to use SelectedList. It comes under the namespace System.Web.Mvc.

This list basically helps you to represent a list that let user to select item.

To start with we will create a Model say SelectListExampleModel.cs


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

namespace SubmitTest.Models
{
    public class SelectListExampleModel
    {
        public SelectListExampleModel()
        {
            if (Items == null)
            {
                Items = new List<Item>();
            }
        }
        public SelectList ItemList { get; set; }
        public List<Item> Items { get; set; }
        public int ItemList1 { get; set; }
    }
    public class Item
    {
        public int ItemId { get; set; }
        public string ItemName { get; set; }
    }
}

HomeController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using SubmitTest.Models;

namespace SubmitTest.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            ViewBag.Message = "Welcome to ASP.NET MVC!";

            //Lets create a list of items here
            

            var selectedList = new SelectListExampleModel();
            Item item = new Item();
            item.ItemId = 1;
            item.ItemName = "Bread";
            selectedList.Items.Add(item);
            Item item1 = new Item();
            item1.ItemId = 2;
            item1.ItemName = "Butter";
            selectedList.Items.Add(item1);
            selectedList.ItemList = new SelectList(selectedList.Items, "ItemId", "ItemName");

            return View(selectedList);
        }
        [HttpPost]
        public ActionResult Index(SelectListExampleModel model)
        {
            ViewBag.Message = "Welcome to ASP.NET MVC!";

          

           var selected= model.ItemList1.ToString();


           return View(model);
        }

        public ActionResult About()
        {
            return View();
        }
    }
}


Lets have a view Named Index.cshtml

@model SubmitTest.Models.SelectListExampleModel

@{
    ViewBag.Title = "Home Page";
}

<h2>@ViewBag.Message</h2>
<p>
    To learn more about ASP.NET MVC visit <a href="http://asp.net/mvc" title="ASP.NET MVC Website">http://asp.net/mvc</a>.
</p>
 @using (Html.BeginForm())
 {
     @Html.DropDownList("ItemList1", Model.ItemList, "- Please Select -")
     <input type="submit" value="Get Selected Value" />
     
 }
  

Happy Coding :)

Thursday, September 13, 2012

MVC3- PartialViewResult as a Modal Dialog

Today we will see how we can display partial view result as a modal dialog

The partial view

 @model ReloadPartial.Models._UserModel  

 @using (Html.BeginForm("Validation","Home", FormMethod.Post, new { id = "UsrValidation" }))  

 {  

   <h3>  

     @Html.ValidationSummary()  

   </h3>  

   @Html.Raw("User Name:")  

   @Html.TextBoxFor(m => m.UserName)  

   <br />  

   @Html.Raw("Email:")  

   @Html.TextBoxFor(m => m.Email)  

   <br />  

   <input type="button" value="!!Action!!" onclick="SubmitForm();" />  

 }  


Now lets see the controller  implementation

 public PartialViewResult Validation(_UserModel model)  
     {  
       ModelState.Clear(); //important to see changes in UI  
       if (ModelState.IsValid)  
       {  
         //Can perform any action 
       }  
       return PartialView("_User",model);  
     }  

JavaScript

 <script language="javascript" type="text/javascript">  
   function SubmitForm() {  
     //select and serialize our small form  
     var frm = $("#UsrData").serialize();  
     // get form action  
     var action = $("#UsrData").attr("action");  
     $.ajax({  
       url: action, // or '@(Url.Action("Validation"))',  
       cache: false,  
       async: true,  
       type: "POST",  
       data: frm, //data to post to server  
       error: function (html) { alert(html); }, //something goes wrong...  
       success: function (data) {  
         showDialog(data);  
       }  
     });  
   }  
 function showDialog(data) {  
    $("#UsrData").html(data);  
   $("#UsrData").dialog({  
     modal: true,  
     title: "Details",  
     resizable: false,  
     open: true,  
     height: 150,  
     width: 200,  
     position: 'center',  
     buttons: [{ text: "Ok", click: function () {  
       $(this).dialog("close");  
       $(this).html('');  
     }  
     }]  
   });  
 }  
 </script  

Thursday, July 19, 2012

Kendo UI: Iterations on Hierarchical data Source

If you are looking into populating the hierarchical data source using Keno framework, First of all you need to use [ kendo.data.HierarchicalDataSource] and the structure should be something like
 var dataSource = kendo.data.HierarchicalDataSource({  
   type: "json",  
   transport: {  
     read: {  
       url: "/test",  
       datatype: json,  
       type: "POST",  
       contentType "application/json;charset=utf-8",  
     }  
   },  
   schema: {  
     model: {  
       hasChildren: "hasChildren"  
     }  
   }  
 });  

Here hasChildren value comes from your controller with the data,depending upon if the parent has any child node attach. so when you return data from controller make sure you have hasChildren field defined and that should be a bool value.

 <div id="dTree">  
 </div>  
 <script type="text/javascript">  
   var Tree;  
   var Root;  
   $(document).ready(function () {  
     Root = new kendo.data.HierarchicalDataSource({  
       transport: {  
         read: {  
           url: document.URL + "/GetTreeData/",  
           dataType: "json"  
         }  
       },  
       schema: {  
         model: {  
           id: "Id",  
           hasChildren: "HasChildren"  
         }  
       }  
     });  
     Tree = $("#dTree").kendoTreeView({  
       dataSource: Root,  
       dataValueField: "Id",  
       dataTextField: "Name",  
       select: function (e) {  
         var selecteddata = null;  
         if ($.browser.msie)  
           selecteddata = Root.getByUid(e.node.attributes[1].nodeValue);  
         else  
           selecteddata = Root.getByUid(e.node.attributes[0].nodeValue);  
         UnitEventArgunments.Selecteddata = selecteddata;  
         UnitEventArgunments.SelectedTreeNode = e;  
         $(document).trigger(OnNodeEvents.OnNodeUnitClicked, UnitEventArgunments);  
       }  
     });  
                //This is the event that will be triggered when node has been added  
     $(document).bind(OnNodeEvents.OnNodetAdded, function (e, args) {  
       refreshTreeView(args);  
     });  
   });  
   function refreshTreeView(e) {  
     
     var uId = new Array();  
     if ($.browser.msie)  
       selectedNodeData = Root.getByUid(e.node.attributes[1].nodeValue);  
     else  
       selectedNodeData = Root.getByUid(e.node.attributes[0].nodeValue);  
     var childData = selectedNodeData.children._data;  
     for (var i = 0; i < childData.length; i++) {  
       uId[i] = childData[i].uid;  
     }  
     for (var j = 0; j < uId.length; j++) {  
       var item = Tree.data("kendoTreeView").dataSource.getByUid(uId[j]);  
       Tree.data("kendoTreeView").dataSource.remove(item);  
     }  
     appendNode(selectedNodeData);  
   }  
   function appendNode(selectedNodeData) {  
     $.post("/GetTreeData", { Id: selectedNodeData.Id },  
         function (data) {  
           Tree.data("kendoTreeView").append(data, $("[data-uid=" + selectedNodeData.uid + "]"));  
         });  
   }  
 </script>  

Friday, June 29, 2012

Kendo UI :Web development framework- Part 2

The MVVM model is most popular now a days . Here we will see with the sample example the use of MVVM in MVC.

To start with  MVVM  we need to first create a View Model, A view model is an observable object. This object has properties and methods. Each property will be bound to something in the HTML. In MVVM, this binding is two way, meaning that if the binding changes on the UI, the model changes, and vice versa.

Let us take a sample example where we will take display a grid and a drop down box, firstly i will create a HTML controls for grid and drop-down. And grid will be using a Template column.

 <script id="rowTemplate" type="text/x-kendo-tmpl">  
   <tr>  
     <td>${ UserName }</td>  
     <td>${ GroupName }</td>  
     <td>  
      <input type="image" id="btnremove" src="/Content/Images/DeleteIcon.gif" data-bind='events { click : removeUser }, enabled: btnSaveIsEnabled' style="width:20px;height:20px;"/></td>  
   </tr>  
 </script>  
 <div id="UserTab">  
   <div id="userGrid" data-role="grid" data-bind="source: User.UsersOf"  
     data-row-template="rowTemplate" data-columns='["User", "Group", "Remove" ]' data-pageable='{"pageSize":10}'>  
   </div>  
   <table style="width: 100; margin-top: 20px; margin-bottom: 20px">  
     <tr>  
       <td style="width: 45%">  
         <select id="dduser" data-role="dropdownlist" data-value-field="Id" data-text-field="Name"  
           data-bind="source: User.AllowableUsers, value: selectedUser, events: { change : userSelectChange }" />  
       </td>  
       <td style="width: 45%">  
         <select id="ddgroup" data-role="dropdownlist" data-value-field="Id" data-text-field="Name"  
           data-bind="source: User.AllowableGroups, value: selectedGroup, events: { change : groupSelectChange }" />  
       </td>  
       <td style="width: 10%">  
         <button id="btnSave" class="k-button" style="width: 75px" data-bind='events { click : addUser }, text: addUserText, enabled: btnSaveIsEnabled'>  
         </button>  
       </td>  
     </tr>  
   </table>  
   <a href='@Url.Action("Create", "Group", new { })' style="color: Blue; text-decoration: true;">  
     Add New Group</a><br />  
   <a href='@Url.Action("Index", "Type", new { })' style="color: Blue; text-decoration: true;">  
     Add New Type</a>  
 </div>  

Here we have created a UserViewModel that is binded to the div id :UserTab, This example also shows how to add and delete user using MVVM pattern.

 <script language="javascript" type="text/javascript">  
   $(document).ready(function () {  
     var UserViewModel = kendo.observable({  
       UserSource: new kendo.data.DataSource({  
         transport: {  
           read: {  
             url: document.URL + "/GetUser/",  
             dataType: "json",  
             type: "post",  
             complete: function (e) {  
               if (UserViewModel.UserSource == null) return;  
               UserViewModel.set("User", UserViewModel.UserSource.at(0));  
             },  
             data: { Id: 0, TypeId: 0 }  
           },  
           update: {  
             url: document.URL + "/AddUserToUser/",  
             dataType: "json",  
             type: "post",  
             complete: function (e) { }  
           },  
           parameterMap: function (options, operation) {  
             if (operation !== "read" && options.models)  
               return { models: kendo.stringify(options.models) };  
             return options;  
           }  
         },  
         schema: {  
           model: { id: "Id" }  
         }  
       }),  
       User: null,  
       selectedGroup: null,  
       selectedUser: null,  
       Id: 0,  
       TypeId: 0,  
       btnSaveIsEnabled: false,  
       addUserText: 'Add',  
       groupSelectChange: function (e) { },  
       userSelectChange: function (e) { },  
       load: function (e) {  
         this.set("Id", e.Id);  
         this.set("TypeId", e.TypeId);  
         this.UserSource.read({ Id: e.Id, TypeId: e.TypeId });  
         $("#dduser").val("").data("kendoDropDownList").text("--Choose User--");  
         $("#ddgroup").val("").data("kendoDropDownList").text("--Choose Group--");  
       },  
       addUser: function (e) {  
         if (this.get("selectedUser") == null || this.get("selectedGroup") == null) {  
           alert("Please select User and Group");  
           return;  
         }  
         if (IsUserExist(this.get("selectedUser").Id, this.get("selectedGroup").Id)) {  
           alert("User already exist");  
           return;  
         }  
         var Id = this.get("Id");  
         var TypeId = this.get("TypeId");  
         $.post("/AddUserToUser", { Id: this.get("Id"), groupId: this.get("selectedGroup").Id, userId: this.get("selectedUser").Id },  
         function (data) {  
           if (data) {  
             UserViewModel.UserSource.read({ Id: Id, TypeId: TypeId });  
             aler("User/Group Added");  
           }  
           else  
             growlSad("User not Added");  
         });  
       },  
       removeUser: function (e) {  
         if (confirm("Are you sure you want to delete this user from group?")) {  
           var Id = this.get("Id");  
           var TypeId = this.get("TypeId");  
           $.post("/DeleteUser", { UserId: e.data.UserId },  
         function (data) {  
           UserViewModel.UserSource.read({ Id: Id, TypeId: TypeId });  
         });  
         }  
       }  
     });  
     kendo.bind($("#UserTab"), UserViewModel);  
     $(document).bind(Events.OnClicked, function (event, args) {  
       UserViewModel.load({ Id: args.Selected.Id, TypeId: args.Selected.TypeId });  
       UserViewModel.set("btnSaveIsEnabled", args.Selected.IsActive);  
     });  
     $(document).bind(window.Events.OnUpdated, function (e, args) {  
       ResetFormUser();  
     });  
     function IsUserExist(userId, groupId) {  
       var gridDataSource = UserViewModel.UserSource._data[0].UsersOf;  
       for (var i = 0; i < gridDataSource.length; i++) {  
         if (userId == gridDataSource[i].UserId && groupId == gridDataSource[i].GroupId)  
           return true;  
       }  
       return false;  
     }  
     function ResetFormUser() {  
       UserViewModel.load({ Id: 0, TypeId: 0 });  
       UserViewModel.set("btnSaveIsEnabled", false);  
     }  
   });  
 </script>  

Happy Coding :) 

Friday, June 8, 2012

Hierarchical-Data in Organization Structure View

While going through an interesting assignment i got to learn how to play with Hierarchical Database where the data in the data base are stored in the following format

Here the main challenge was to display the data in the following format


As we have may tree view structure available in the market, but they don't provide a org structure look & feel.

I took the reference of  http://dl.dropbox.com/u/4151695/html/jOrgChart/example/example.html and created a customized structure using which we can dynamically create organization structure.

Bellow is the location where i have kept the code and Database

Display-Hierarchical-Data Source Code
Database

When you build and run the code you need to provide the path as

http://localhost:[Port Number]/employeeTree/index

Happy Coding :)


Friday, May 18, 2012

Using Model Metadata

When we are using Runtime Scaffolding to generate view, We are using @Html.EditorForModel() so here it will populate the model for editing but if we want some fields that should be non editable that we use the model meta data feature, The name space that we need to include is System.Web.Mvc .

Following are some of its attribute that we can use:
  • [HiddenInput] : If we don't want the property to be editable
  • [HiddenInput(DisplayValue=false)] :  If we don't want to display the value.
The Fields will be generated in the html but the value will be hidden.  If you are using [ScaffoldColumn(false)] the column will not be generated.

Bellow is the example that explains the usage.
-------------------------------------------------------------------------------------------------------------
 using System;  
 using System.Collections.Generic;  
 using System.Linq;  
 using System.Web;  
 using System.ComponentModel.DataAnnotations;  
 using System.Web.Mvc;  
 namespace Using_Model_Metadata.Models  
 {  
   public class Product  
   {  
     [HiddenInput]  
     public int Id { get; set; }  
     public string Name { get; set; }  
     public string Category { get; set; }  
     public decimal Price { get; set; }  
   }  
 }  
 -------------------------------------------------------------------------------------------------------------  
 using System;  
 using System.Collections.Generic;  
 using System.Linq;  
 using System.Web;  
 using System.Web.Mvc;  
 using Using_Model_Metadata.Models;  
 namespace Using_Model_Metadata.Controllers  
 {  
   public class ProductController : Controller  
   {  
     //  
     // GET: /Product/  
     public ActionResult Index()  
     {  
       return View(GetProduct());  
     }  
     public Product GetProduct()  
     {  
       Product product = new Product { Id = 1, Name = "Kayak", Category = "Watersports", Price = 275m };  
       return product;  
     }  
   }  
 }  
 -------------------------------------------------------------------------------------------------------------  
 @model Using_Model_Metadata.Models.Product  
 @{  
   ViewBag.Title = "Index";  
 }  
 <h2>Index</h2>  
 @Html.EditorForModel()  
-------------------------------------------------------------------------------------------------------------
Output

Thursday, May 17, 2012

Rendering a Child Action

You can invoke a child action using the Html.Action helper. With this helper, the action method is
executed, the ViewResult is processed, and the output is injected into the response to the client.



Below is the example that explain how you can implement child Action
 using System;  
 using System.Collections.Generic;  
 using System.Linq;  
 using System.Web;  
 using System.Web.Mvc;  
 namespace child_Action.Controllers  
 {  
   public class ChildActionController : Controller  
   {  
     //  
     // GET: /ChildAction/  
     public ActionResult Index()  
     {  
       return View();  
     }  
     public ActionResult ChildActionDemo()  
     {  
       return View();  
     }  
     [ChildActionOnly]  
     public ActionResult Time()  
     {  
       return PartialView(DateTime.Now);  
     }  
   }  
 }  
 --------------------------------------------------------------------------------------------------------------  
 View -> ChildAction->ChildActionDemo  
 @{  
 ViewBag.Title = "Child Action Demonstration";  
 }  
 <p>This is the method rendered by the action method</p>  
 @Html.Action("Time")  
 <p>This is the method rendered by the action method again</p>  
 --------------------------------------------------------------------------------------------------------------  
 Partial View: Shared->Time  
 @model DateTime  
 <p>The time is: @Model.ToShortTimeString()</p>