Tips & Tricks on ASP.NET MVC, Ajax, jQuery, Entity Framework

Column Attribute in Entity Framework 5

When developing applications using Entity Framework code first approach, you may use Column data annotation on your model properties to define what attributes that property has, ex : name, type etc.

in Entity Framework 4.3.1,  ColumnAttribute is defined in System.ComponentModel.DataAnnotations namespace which is available in EntityFramework.dll. So you need to add a reference to EntityFramework.dll and include a using statement in your class to use that.

using System.ComponentModel.DataAnnotations;
namespace YourProject.Models
{
    public class User
    {
        public int CustomerID { set; get; }

        [Column(TypeName = "ntext")]
        public string AboutText { get; set; }
    }
}

 

But in EntityFramework 5, If you use the same code, you will get a compile time error like below

The type or namespace name 'ColumnAttribute' could not be found (are you missing a using directive or an assembly reference?)

The reason for this error is, in  Entity Framework 5, they moved the ColumnAttribute class to a different namespace called System.ComponentModel.DataAnnotations.Schema. So you need to add a using statement to include that namespace too in your model class.

using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace YourProject.Models
{
    public class User
    {
        public int CustomerID { set; get; }

        [Column(TypeName = "ntext")]
        public string AboutText { get; set; }
    }
}

People usually get this error, when they follow a book which has sample code which uses Entity Framework 4.3.1 and they try to create the project and download Entity Framework via nuget where they will get the latest version, Entity framework 5 ( at the time of this post). Adding the relevant namespace will fix the issue.

More info in msdn,

ColumnAttribute class

System.ComponentModel.DataAnnotations.Schema Namespace

If interested, you can see the source code by checking the class in any assembly decompiling tools.

ColumnAttribute in EntityFramework 5

 

TechiesWebMetro wordpress theme

I created a new wordpress theme and thought of sharing back to the community :) .

I was not doing any kind of wordpress stuff for the past 2-3 years, but  happened to attend the wonderful ann arbor give camp this year where our team did some wordpress customization(which includes a custom theme creation) for the non-profit organization we were working with. This made me think about creating a new theme and i jumped in!

This theme is developed on top of StudioPress theme from dailyblogtips.  My special thanks to them. :)

I named the theme as “TechiesWebMetro”.  Hope you like it.

TechiesWebMetro WordPress theme

I updated this blog to my new theme. So you must be feeling the new theme now :)

You can download the  theme here.

ASP.NET MVC3 Tree View with jsTree

In ASP.NET MVC, There is no server controls like what we have in Web forms to render TreeView/ Menu, We need to write our own markup to do so. Even in all those webforms controls, it is generating some HTML which renders a tree or a menu. Here we are going to create an ASP.NET MVC3 Tree View with jsTree plugin.

MVC3 Tree View with jsTree

We will be creating an organizational tree which shows a hierarchical representation of who works for whom in an organization. We will have a table which stores the employee information along with who their manager is like below. I used SQL Server Compact Edition database in this project to store our data. To render the tree,  we are using jsTree plugin which converts our ul-li elements to a tree structure.

mvc3 tree view

Each Employee record has a ManagerID which tells who is the manager of that employee. I set the First employee’s ManagerID value as NULL, because he is the President of the company and he do not have any manager.

Now, Let’s create a model to represent the employee. we will create a POCO Class like this.

model for mvc3 tree view

 

Now we need a data access method to read data from our SQLServer compact database and return a list of  UserViewModel object. Since my demo program stores table in SQL Server compact edition database, i am using SqlCeConnection class and SqlCeCommand class to talk to it and get data.These two classes belongs to System.Data.SqlServerCe namespace. You need to add a using statement to import this namespace to your data access class.

 

So GetAllUsers method with give us a list of User class objects

 

 

Now we need to convert this list of objects (which is  a sequential list) to hierarchical form. that means, All the employees belongs to Joe, should be listed in his Employees property. So Let’s do some tricky code here to change the sequential list to hierarchical structure. So Let’s do that in our action method.

hierarchical objects for mvc3 tree view

You can see that we are getting a list of Employee objects using our data access method and then getting the president of the company who does not have any manager so that we can show him as the first /top node of the organization tree.(Assuming that we will have only one president). We are getting the user object which has a null value for the ManagerID column as the president.

Setting the child objects.

After getting the president node, We are going to call SetChildren method which accepts an  Employee Model and the List of Total Users/Employees and then finding out the children / Employees reports to this employee. We are  doing recursion to set the children because we do not know how many layers of employees will be there in the hierarchy. Recursively calling the SetChildren function will set the child Employees for all the employees and at the end of that we will be getting a single Employee object with Children property properly filled.

And if you expand the Employees property further you can see the employees works under this employee.

Now let’s update our view to have the sufficient markup to render the tree. Since we are using  jsTree, We need to include jsTree library to the page. I included the default css file also. I updated the css file to show a user  icon instead of showing the default directory icon.

Our view is strongly typed to Employee class, which will be representing the president / top node of the hierarchy.  After printing the Name property value of the first node, We are calling a partial view called Children and passing our Model to that. So i created a partial view called Children.cshtml under the same view folder and have markup like this

 

You can see recursion here also. We are calling the Childrens partial view recursively to render the child’s for each node.

Now let’s see how  it works when you run the project.

You can customize the tree look and feel by changing the css  or playing with the options of  jsTree. You can download a working sample which i created to write this post here.

Hope this helps. Do not forget to leave a comment, if this post was useful to you. :)

 

 NSUGX3J7C2U3

 

ASP.NET MVC3 Dynamically added form fields model binding

Adding  new Item to a list of items, inline is a very nice feature you can provide to your user. This posts shows 2 different ways to do this in ASP.NET MVC3 and how Modelbinding handles that.

MVC3 dynamically added form fields model binding

We are going to create a new page where it lists the various Programming Interests a user has.  The user will have an option to add a new Record ( Programming interest) to the list present.

Let’s create 2 ViewModels(ViewModel is a simple POCO class) for our views. Add the below 2 classes to our project.

public class User
{
    public int Id { set; get; }
    public string Name { get; set; }   
    public IList<UserInterest> Interests { get; set; }
}
public class UserInterest
{
    public int Id { set; get; }
    public string InterestText { set; get; }
    public bool IsExperienced { set; get; }
}

Now I am going to create a GET action which returns a User class object with his interests.

public ActionResult ClientSideCreation()
{
    var usr = new User();
    usr.Name = "Jon Skeet";
    usr.Interests = GetUserInterests();
    return View(usr);
}

This action is simply creating an object and setting the Name property and Setting the Interests collection. GetUserInterests is a method which returns a list of UserInterest object.

Now to handle the collection Property of our Model, Let’s create an Editor template called  UserInterest.cshtml under Home\EditorTempaltes.

Editor Template

Now we will use Html.EditorFor HTML Helper method to bring this editor template to our main view.

@model MvcApplication2.Models.User
@using(Html.BeginForm())
{ 
 <h3>Name : @Model.Name</h3>
 <h4>Interests</h4>   
 <div class="divIntersts">
    <table  id="container">
     <tr>
        <th>Name</th><th>Have Experience?</th>
     </tr>
     @Html.EditorFor(x => x.Interests)    
    </table>   
 </div>
 <p><input type="submit" value="Save" /></p>
}

We are done with that. Running the project will show the output like this.
EditorTemplate showing a collection of Items

note that this does not have any feature for the user to add the new record to the collection.

Adding Record Inline

I am going to make some changes to our view.

1) Add a button called ” Add new Item ” to our html markup.

<input type="button" id="btnAdd" value="Add New Item" />

2) Add some javascript code to create the form fields when user clicks on the Add New Item button and append that to our table which holds the collection.

    $(function () {
        $("#btnAdd").click(function (e) {
            var itemIndex = $("#container input.iHidden").length;
            e.preventDefault();
            var newItem = $("<tr><td><input id='Interests_" + itemIndex + "__Id' type='hidden' value='' class='iHidden'  name='Interests[" + itemIndex + "].Id' /><input type='text' id='Interests_" + itemIndex + "__InterestText' name='Interests[" + itemIndex + "].InterestText'/></td><td><input type='checkbox' value='true'  id='Interests_" + itemIndex + "__IsExperienced' name='Interests[" + itemIndex + "].IsExperienced' /></tr>");
            $("#container").append(newItem);
        });
    });

So the result of running our updated project will be like this. there is a “Add New Item” button and clicking that will add new record to our existing table.

Now When the user posts the form, the MVC Model binding feature will bind the newly added items as well. You can check that by putting a breakpoint in the HttpPost action method.

 

The trick is to keep the id property value of the html element in this format.

CollectionName_ItemIndex__PropertyName

and name property value in this format

CollectionName[ItemIndex].PropertyName

If your Collection item has many fields, It will be hard to write javascript code for creating the form elements. In that case, You may consider doing it in the server side.

So i will update my javascript code like this.

$(function () {
    $("#btnAdd").click(function (e) {
        var itemIndex = $("#container input.iHidden").length;       
        e.preventDefault();
        $.get("@Url.Action("NewInterestRow", "Home")/"+itemIndex,function(data){
            $("#container").append(data);
        });           
    });
});

You can see that we are not building the html in our client side code here. Instead we are mkaing an ajax call to the NewInterestRow action method and passing the Index of the new item. So we need to create that action method like this.

public ActionResult NewInterestRow(int id)
{
    var interest = new UserInterest { Id=id};
    return View("Partial/NewInterestRow",interest);
}

 

It simply creates an object of our UserInterest class and set the Id  property value of it as the values passed to this method (which is the Item Index of the new item to be created) .Then we are passing that object to a partial view called NewInterestRow. So Lets create a new View under Home/Partial called NewInterestRow.cshtml with the below content.

 

 

@model MvcApplication2.Models.UserInterest
@{    Layout = null; }
<tr> 
 <td>
  <input type="hidden" id="Interests_@(Model.Id)__Id" class="iHidden"  name='Interests[@Model.Id].Id' />
  <input type='text' id='Interests_@(Model.Id)__InterestText'   name='Interests[@Model.Id].InterestText'/>
 </td>
 <td>
    <input type='checkbox' value='true'  id='Interests_@(Model.Id)__IsExperienced' name='Interests[@Model.Id].IsExperienced' />
 </td>
</tr>

This View also creates the same HTML elements we created at client side previously, with the same name /ID convention we need for the Model binding to work.

 

Summary : Here we showed 2 ways to add dynamic form fields to an existing collection which gives a nice user experience and how MVC Model binding works for those new elements. The main thing to remember is to keep the format of the name and id property values. Model binding will work for the new elements only if they follow the format.

You can download the sample source code here to see how it works.