http://www.imomin.webs.com

Thank You for Visit Me

Md. Mominul Islam

view:  full / summary

Sehri And Iftar Schedule For All District

Posted by imomins on July 22, 2012 at 5:55 AM Comments comments (0)


Sehri And Iftar Schedule For All District

Posted by imomins on July 22, 2012 at 5:55 AM Comments comments (0)


HSC Result in PDF Formate Collegewise..

Posted by imomins on July 18, 2012 at 8:50 AM Comments comments (0)

PDF আকারে সবার আগে HSC RESULT নিয়ে নিন!





আমি এখানে আলোচনা করব ফলাফল পাবার ৩ টি উপায় নিয়ে। ৩য় টি পিডিএফ আকারে!

১। SMS RESULT:

আপনি বাংলাদেশের সকল মোবাইল অপারেটরদের SMS সেবার মাধ্যমে আপনার ফলাফল পেতে পারেন (গ্রামীণফোন, বাংলালিংক, রবি, এয়ারটেল, টেলিটক ও সিটিসেল;)
কিভাবে? নিচে দেখুন ...

  • 1. আপনার মোবাইল ফোন এর এসএমএস অপশনে গিয়ে নতুন মেসেজ তৈরি করুন।
  • 2. টাইপ করুন আপনার এইচএসসি শিক্ষা বোর্ডের প্রথম ৩ অক্ষর <স্পেস> আপনার রোল নম্বর <স্পেস> আপনার পাশের বছর
  • 3. পাঠিয়ে দিন এটি 16222 নাম্বারে।
  • 4. অপেক্ষা করুন যতক্ষণ আপনি ফলাফল সহ আপনার মোবাইলে একটি মেসেজ পান!

উদাহরণ...

HSC DHA 123456 2012
HSC COM 123456 2012
HSC RAJ 123456 2012
HSC CHI 123456 2012
HSC JES 123456 2012
HSC SYL 123456 2012
HSC BAR 123456 2012
HSC DIN 123456 2012

আপনি যদি আলীম পরীক্ষার্থী হন, তাহলে ALIM লিখুন HSC এর জায়গায়।

আপনি যদি ভকেশনাল পরীক্ষার্থী, তাহলে TECH লিখুন HSC এর জায়গায।

অন্যান্য সব একই রকম হবে।
এখানে, 123456 হল একটি রোল নম্বর, আপনার নিজের রোল নম্বর বসান এই জায়গায়।

২। ONLINE INDIVIDUAL RESULT:

এইটা কিছুটা অসম্ভব হয়ে যেতে পারে। কারণ, ফল প্রকাশের পর পর পরীক্ষার্থী ও তাদের আত্মীয়স্বজন সবাই একই ওয়েব এড্রেসে অনুসন্ধান করে।
তবুও আপনি এই ঠিকানায় অথবা এই ঠিকানায় অনুসন্ধান চালাতে পারেন।

৩। PDF TOTAL RESULT:

এই উপায়ে সবচেয়ে তাড়াতাড়ি ফলাফল পাবার আশা করতে পারেন।

এই জন্য, আপনি নিম্নলিখিত ধাপগুলি অনুসরণ করতে হবে...

  • 1. এখানে ক্লিক করুন, ডাউনলোড করুন আপনার কলেজের EIIN নাম্বার।
  • 2. ডাউনলোড করে ফাইলটি খুলে দেখে নিন আপনার শিক্ষা প্রতিষ্ঠান এর EIIN NUMBER টি .
  • 3. এবার এখানে ক্লিক করুন। ইমেল ঠিকানা ও পাসওয়ার্ড দিয়ে লগইন করুন।

[ইমেল ঠিকানা এরকম হবেঃ

[email protected]

এখানে, DHA = আপনার বোর্ড ,
136528 = আপনার কলেজের EIIN NUMBER টি,
PASSWORD = আপনার কলেজের EIIN NUMBER টি, উপরোক্ত ক্ষেত্রে, 136528 ]

  • 4. লগ ইন করার পর ইনবক্স দেখুন। নতুন মেইল থাকবে attachment (PDF) সহকারে।
  • 5. ATTACHMENT এর উপর ক্লিক করে পিডিএফ ডাউনলোড করুন।

hi

Posted by imomins on July 13, 2012 at 9:20 AM Comments comments (0)

hi

????? ????? ????? ?? ?? ??????? ????

Posted by imomins on July 13, 2012 at 9:20 AM Comments comments (0)

সম্প্রতি ইয়াহুর সার্ভার হ্যাক করে ৪৫ হাজারের বেশি পাসওয়ার্ড হাতিয়ে নিয়েছে হ্যাকাররা। এসব হ্যাক করা পাসওয়ার্ডের তথ্য ফাঁস করেছে অনলাইনে।
ইয়াহুতে ব্যবহূত পাসওয়ার্ড অনলাইনের অন্য কোনো অ্যাকাউন্টে ব্যবহার করা হলে সে অ্যাকাউন্টের তথ্যও হাতিয়ে নিচ্ছে হ্যাকাররা। কিছুদিন আগে একইভাবে লিঙ্কডইনের অ্যাকাউন্টও হ্যাক করে তথ্য হাতিয়ে নিয়েছে তারা।
তথ্যের নিরাপত্তা রক্ষায় কম্পিউটার নিরাপত্তা বিশেষজ্ঞরা দ্রুত পাসওয়ার্ড পরিবর্তন করে নিতে পরামর্শ দিয়েছেন। ইয়াহু, জিমেইল, লিঙ্কডইন, এমএসএন হটমেইল, কমক্যাস্ট ও এওএল অ্যাকাউন্ট হ্যাক হয়ে গেছে কি না, তা পরীক্ষা করে নেওয়ার জন্য সিকিউরি ম্যালওয়্যার ল্যাব একটি সেবা চালু করেছে।
http://labs.sucuri.net/?yahooleak লিঙ্কে ব্রাউজ করে অ্যাকাউন্ট হ্যাক হয়েছে কি না, তা পরীক্ষা করা যাবে।

Simple .NET MVC 3 web application with integrated Facebook OAuth API

Posted by imomins on June 13, 2012 at 9:50 AM Comments comments (0)

Introduction

Before creating a .NET MVC application, we have to register the domain name that will be used for the web site at the Facebook development site: http://developers.facebook.com/setup/. After successful registration, we will have a Facebook APIKey and Facebook Secret.

Now let's create a simple ASP.NET MVC application in VS:


I will use the Facebook API button in this sample to show an alternative log in option to the user. Let's change the _LogOnPartial.cshtml file in such a way:

@if(Request.IsAuthenticated) {
    <text>Welcome <strong>@User.Identity.Name</strong>!
    [ @Html.ActionLink("Log Off", "LogOff", "Account") ]</text>
}
else {
    <fb:login-button perms="email,user_checkins" onlogin="afterFacebookConnect();" 
       autologoutlink="false" ></fb:login-button>
    <div id="fb-root" style="display:inline; margin-left:20px;"></div>
    @:[ @Html.ActionLink("Log On", "LogOn", "Account") ]
}
<script language="javascript" type="text/javascript">
    window.fbAsyncInit = function () {
        FB.init({ appId: ' -- YOUR REAL APPLICATION ID SHOUD BE HERE --', 
                  status: true, cookie: false, xfbml: true });
    };
    function afterFacebookConnect() {
        FB.getLoginStatus(function (response) {
            if (response.session) {
                window.location = "../Account/FacebookLogin?token=" + 
                       response.session.access_token;
            } else {
                // user clicked Cancel
            }
        });
    };
    $(document).ready(function () {
        if (document.getElementById('fb-root') != undefined) {
            var e = document.createElement('script');
            e.type = 'text/javascript';
            e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
            e.async = true;
            document.getElementById('fb-root').appendChild(e);
        }
    });
</script>

The following elements were added to the control:

  • Facebook login button (fb:login-button).
  • Container which will contain all Facebook scripts (div id="fb-root").
  • FB initialization script (FB.fbAsyncInit). You have to replace the sample appId value with the real one received when registering your app on the Facebook development site.
  • afterFacebookConnect - script which will be called after the user closes the Facebook login dialog window (after successful or failed login).
  • Script for loading Facebook JavaScript libraries (e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';).

After successful login, we will have the access_token value, and now we can load detailed user's info, store this info (if we need to), and authenticate the user. To do this, we will redirect the user to the Account.FacebookLogin action and pass the access_token value as a parameter to this action. So at this stage, we will implement the "FacebookLogin" action. The created action will look like this:

using System.Web.Mvc;
using System.Web.Security;
using MVCOAuth.Models;
using System.Net;
using Newtonsoft.Json.Linq;
using System;

namespace MVCOAuth.Controllers
{
    public class AccountController : Controller
    {
        [HttpGet]
        public ActionResult FacebookLogin(string token)
        {
            WebClient client = new WebClient();
            string JsonResult = client.DownloadString(string.Concat(
                   "https://graph.facebook.com/me?access_token=", token));
            // Json.Net is really helpful if you have to deal
            // with Json from .Net http://json.codeplex.com/
            JObject jsonUserInfo = JObject.Parse(JsonResult);
            // you can get more user's info here. Please refer to:
            //     http://developers.facebook.com/docs/reference/api/user/
            string username = jsonUserInfo.Value<string>("username");
            string email = jsonUserInfo.Value<string>("email");
            string locale = jsonUserInfo.Value<string>("locale");
            string facebook_userID = jsonUserInfo.Value<string>("id");

            // store user's information here...
            FormsAuthentication.SetAuthCookie(username, true);
            return RedirectToAction("Index", "Home");
        }

And that's it! We have integrated alternative Facebook authentication on the MVC site. Before login:


After successful Facebook authentication:


Hope this will be helpful for someone! 

How to Integrate Asp.Net application in Facebook

Posted by imomins on June 13, 2012 at 9:50 AM Comments comments (0)

How to Integrate Asp.Net application in Facebook

(function() { var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true; po.src = 'https://apis.google.com/js/plusone.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s); })();

 

Hi,

Someone asked me how to create facebook app day before yesterday and he wanted to integrate existing asp.net webpage in this facebook app. I was not much aware about facebook integration but got to know that facebook doesn’t have any api for asp.net to integrate webpage instead they have for php and python. So I googled and then find very good dotnet toolkit for facebook app which is from Microsoft (Facebook Developer Kit). We can integrate desktop or web app using this toolkit. So I thought I should make a sample app and share on this platform.

Below are some steps":

Before creating facebook app you need to have facebook account.

Setting up Facebook App
  • To create facebook app click on Developer section 
  • Click on Set up New App button.
  • Agree Facebook terms and click on Create App

Fb_CreateApp_thumb1

  • Put Security Check keywords.
  • Click on Submit.
  • Fill basic information about app.

fb_BasicInfo_thumb1

  • Click on Facebook Integration tab.
  • Put Name of Canvas page.
  • Before putting URL of webpage of your website, I want to show how your page can get callback from facebook app. So first we create webpage in our website:
  • Create asp.net website in Visual studio.
  • Add reference of Facebook.dll from “C:\Program Files\Coding4Fun\Facebook\Binaries”. This dll will be placed after installing Facebook Developer kit on your machine.
  • Create instance of FacebookService object. you can copy facebook app api key and secret key from application page on facebook in source code.

 

fb_appkey_thumb1

put above values in FACEBOOK_API_KEY and FACEBOOK_SECRET constants respectively.

you can get user_id of facebook who requested this application by calling

1.string userId = Session["Facebook_userId"] as String;

you can also get many information about user like name, sex, location,friends etc.

1.User usr=_fbService.GetUserInfo();

fb_userInfo_code_thumb2

Source Code

01.using System;
02.using Facebook;
03.public partial class Facebook_ConnectFacebook : System.Web.UI.Page
04.{
05.    Facebook.Components.FacebookService _fbService = new Facebook.Components.FacebookService();
06.    private const string FACEBOOK_API_KEY = "191856207506775";
07.    private const string FACEBOOK_SECRET = "820c0b05b14a09365e072c8d37a8c49f";
08. 
09.    protected void Page_Load(object sender, EventArgs e)
10.    {
11.        _fbService.ApplicationKey = FACEBOOK_API_KEY; _fbService.Secret = FACEBOOK_SECRET;
12.        _fbService.IsDesktopApplication = false;
13.        string sessionKey = Session["Facebook_session_key"] as String;
14.        string userId = Session["Facebook_userId"] as String;
15.         
16.    // When the user uses the Facebook login page, the redirect back here
17.    // will will have the auth_token in the query params
18.         
19.    string authToken = Request.QueryString["auth_token"];
20.         
21.    // We have already established a session on behalf of this user
22.        if (!String.IsNullOrEmpty(sessionKey))
23.        {
24.            _fbService.SessionKey = sessionKey; _fbService.UserId = userId;
25.        }
26.        // This will be executed when Facebook login redirects to our page        
27.        else if (!String.IsNullOrEmpty(authToken))
28.        {
29.            _fbService.CreateSession(authToken);
30.            Session["Facebook_session_key"] = _fbService.SessionKey;
31.            Session["Facebook_userId"] = _fbService.UserId;
32.            Session["Facebook_session_expires"] = _fbService.SessionExpires;
33.        }
34.        // Need to login        
35.        else
36.        {
37.            Response.Redirect(@"http://www.Facebook.com/login.php?api_key=" + _fbService.ApplicationKey + @"&v=1.0\");
38.        }
39. 
40.        User usr = _fbService.GetUserInfo();
41.        string t = string.Format("User Name:{0}, Sex:{1}, Location: {2}", usr.Name, usr.Sex, usr.CurrentLocation.City);
42.        Response.Write(t);
43.    }
44.}
Testing

    

Now we are done with coding. Its time for testing.

  • Run your website.
  • Put webaddress of your webpage in facebook developer section as canvas URL.
  • Canvas type should be IFrame.

fb_canvasUrl_thumb1

  • Click on Save changes.
  • now Facebook app has created.

image_thumb2

  • Now open app url like http://apps.facebook.com/testneeraj/ on browser .
  • First time authToken will not authorize from facebook because you need to agree on “Allow Access” information.
image_thumb4
  • Click on facebook banner.
  • It will ask Request for Permission. Click Allow.

image_thumb10

  • It will show all basic information of user on webpage.

image_thumb15

  • After that you can publish your app but having restriction from facebook that your application should 10 active member per month.

 

I hope this article will give good knowledge about integration with facebook app. Please share your comments and feedback with me.

????? ???????????? ??????? ??????? ?????? ????????

Posted by imomins on June 11, 2012 at 8:00 AM Comments comments (0)



ভুমি সংক্রান্ত পরিমাপক কাজে ব্যববহারের জন্য রাজশাহী প্রকৌশল ও প্রযুক্তির বিশ্ববিদ্যালয়ের (রুয়েট;) শিক্ষার্থী মো. আল হেলাল ডিজিটাল পরিমাপক যন্ত্র আবিস্কার করেছেন । তিনি বিশ্ববিদ্যালয়ের সিভিল ইঞ্জনিয়ারিং বিভাগের ৪র্থ বর্ষের শিক্ষার্থী।

 

তিনি বলেন, ‘জমি অথবা যেকোন পরিমাপক হিসেবে সাধারণভাবে আমারা ফিতা বা স্কেলের ব্যবহারকেই বুঝি। এতে সময়ের যেমন অপচয় হয় তেমনই প্রায়শঃই র্নিভুল পরিমাপও সম্ভব হয় না। কিন্তু ডিজিটাল পরিমাপ যন্ত্রের সাহায্যে যেসব যায়গায় ফিতা বা চেইন নিয়ে মাপা সম্ভব নয় যেমন নদীর ভিতরে কোন ব্রিজের উচ্চতা বা কোন উচু ভবনের কোন অংশের দৈর্ঘ্য ইত্যাদি এ যন্ত্রের সাহায্যে দূর থেকেই মাত্র কয়েকটি বাটন চাপ দেওয়ার মাধ্যমে র্নিভূল তা নির্ণয় করা যাবে।’

তিনি আরো বলেন, ‘এমনকি এজন্য নিজের অবস্থান পরিবর্তন করে বস্তুর নিকট যাওয়ারও দরকার নেই। আর সবচেয়ে বড় সুবিধা হল দূরত্বটি প্রদর্শিত হবে ডিজিটাল ডিস্পেলেতে। তাই অত্যান্ত সুক্ষ এমনকি দশমিক এর পরে প্রায় ৪-৫ ঘর পর্যন্ত মান নেওয়া যাবে। যা ফিতা দিয়ে মেপে বের করা প্রায় অসম্ভব।’

তাছাড়া. দেশীয় প্রযুক্তিতে তৈরী এ যন্ত্র তৈরীতে ব্যবহৃত হয়েছে সি প্রোগামিং এবং মাইক্রোপ্রসেসর চিপ। ফলে এর উৎপাদন খরচও অনেক কম। মাত্র ২-৩ হাজার টাকার মধ্যেই এ যন্ত্র তৈরী করা সম্ভব।

 

এ প্রকল্পের জন্য বিভিন্ন প্রয়োজনে বিভাগের শিক্ষক ড. কামরুজ্জামান (নয়ন;) সবচেয়ে বেশী সহযোগীতা করেন বলেও তিনি জানান।

ড. কামরুজ্জামান নয়ন জানান, ডিজিটাল যুগে পরিমাপে ফিতা বা স্কেলের এই ধারনা থেকে বের করে আনার জন্যই হেলালের এ প্রচেষ্টা। যা তিনি বাস্তবে রুপ দিতে সক্ষম হয়েছেন।

তিনি বলেন, শিক্ষকদের উদ্যোগে সোমবার বিশ্ববিদ্যালয়ে এ প্রকল্পটিকে নিয়ে একটি প্রদর্শনীর আয়োজন করা হয়। প্রদর্শনীতে অন্যান্যদের মধ্যে উপস্থিত ছিলেন রুয়েটের উপাচার্য ড.সিরাজুল করিম চৌধুরী এবং প্রকৌশল বিভাগের শিক্ষকবৃন্দ।
প্রকৌশল বিভাগের সিনিয়র শিক্ষক প্রফেসর ইকবাল মতিন এ আবিষ্কারে প্রসঙ্গে বলেন ‘এটি আসলেই একটি প্রশয়সনীয় উদ্যোগ। সরকারী বেসরকারী পৃষ্ঠপোষকতা পেলে এ যন্ত্রকে বাহিরেও রপ্তানী করা সম্ভব হবে”।

AJAX based CRUD tables using ASP.NET MVC 3 and jTable jQuery plug-in

Posted by imomins on June 5, 2012 at 10:15 AM Comments comments (0)

jTable overview
A full-featured jTable instance. Try a live demo here.

Contents

Introduction to the problem

When we are developing a 'data manipulation page', we almost always do the same thing: A 'table/grid' that is used to 'show records' of a table in a database, a 'create new record' page/dialog to add a new record to the database, an 'edit record' page/dialog to edit a record, and finally a way of 'deleting a record' in the database.

Also, using AJAX, we can create more fast and interactive pages. Especially, jQuery and jQueryUI are invaluable libraries to perform manipulation in an HTML page and perform AJAX requests to the server.

Users no longer need to leave the 'list of records' page to create/edit or delete a record. Also, the page never refreshes itself to reflect a change in records. When the user deletes a record in the table, we can delete the corresponding row from the table without refreshing the whole page. When the user edits a record and saves it, we can change the corresponding values in the table, and so on... Also, we can do some animations while deleting, creating, or updating records.

All of the subjects I mentioned above are known techniques and we have all implemented them. But the problem is that, we are developing/coding almost the same page for every type of record. Surely, we can copy/paste/modify it! But is it a solution or another mess? All we know is, copy/paste is not desirable for all kinds of programming, it is an evil!

What is jTable

jTable [1] is a jQuery plug-in that addresses the problem mentioned above. It takes a list and properties of fields of a record and does all the job! It has several features:

  • Automatically creates an HTML table and loads records from the server using AJAX.
  • Automatically creates a 'create new record' jQueryUI dialog form. When the user creates a record, it sends data to the server using AJAX and adds the same record to the table in the page. 
  • Automatically creates an 'edit record' jQueryUI dialog form. When the user edits a record, it updates the server using AJAX and updates all the cells on the table in the page.
  • Allow the user to 'delete a record' by jQueryUI dialog based confirmation. When the user deletes a record, it deletes the record from the server using AJAX and deletes the record from the table in the page.
  • Supports server side AJAX based paging and sorting.
  • Allows user to select rows from table.
  • Allows user to resize columns.
  • Supports unlimited level of master/child tables.
  • Shows animations for create/delete/edit operations on the table.
  • Exposes some events to enable validation with forms.
  • It can be localized easily.
  • Table, forms and other elements are styled in a well defined and commented CSS file.
  • It comes with four pre-defined color themes: blue, red, green and purple, for now.
  • It is browser/platform independent and works on all common browsers.
  • It is not dependent on any server-side technology such as ASP.NET MVC, and can be used with others.
  • It has direct support for ASP.NET Web Forms Page Methods.

Live demo

You can try out a demonstration here: http://www.jtable.org.

A sample page with ASP.NET MVC 3 and jTable

Here I will show how to develop a data manipulation page with ASP.NET MVC 3 and jTable. This sample project is included in the download file.

Assume that we are manipulating a Person list that has a lot of information: name, city, email, password, gender, birth date, an 'about' text, and education.

Using the page

First, I will show the capabilities of jTable. Here is the list of people:

The Person List

This table is automatically created by jTable. (Don't worry about the style of the table. The HTML code of the table is not styled and is a clean HTML table. You can edit the CSS files easily.) Also, it shows only the desired fields. Edit/Delete images (buttons) are completely optional, and they are also automatically added to each row. Title is also optional and the add new record link is changeable by the user with another element in the page. While the records are being loaded, a 'loading...' animation is shown.

When the user clicks the add new record link, a jQueryUI dialog based form is opened:

Creating new record

This form is also completely automatically created based on the fields of the record! When you fill the form and save, jTable serializes the form and performs an AJAX call to the server. If the server responds 'OK', it adds the record to the table with an animation:

Added new record animation

In the animation above, the row is highlighted with green. It turns back to normal color after a few seconds. This animation is just a CSS class transition and can be changed in the CSS file easily. So you can change the animation to whatever you want. If the server returns error while adding the record, jTable automatically shows an error dialog message and does not add the record to the table.

If you click the edit image (button) in a row, jTable automatically creates an editing jQuery dialog form:

Editing a record

jTable automatically creates and fills the form with the selected record's values. When the user saves the form, just like creating a new record, the record is saved to the server. If the AJAX call is a success, the record values are updated in the table and an 'edited' animation is shown:

Editing Record Animation

As I mentioned above when creating the record, same animation mechanism does exist while updating an edited record in the table. An edited row turns to normal style in a few seconds.

When the user clicks the delete image (button), jTable shows a confirmation dialog:

Delete confirmation dialog

If the user clicks the delete button, the record is deleted from the server using an AJAX call. If the operation succeeds, it is also removed from the table automatically with a deleting animation:

Deleting animation

The deleting row is highlighted for a second and removed from the table.

Now we will see how to implement the page above in ASP.NET MVC 3.

Model

We have two classes here: Person (represents a record in the People database table) and City (represents a record in the Cities database table). A person lives in a city. So the Person class has a CityId that is the ID of a city row in the Cities table.

The Person class is shown below:

public class Person
{
    public int PersonId { get; set; }

    // Id of a City in Cities
    [Required]
    public int CityId { get; set; }

    [Required]
    public string Name { get; set; }

    [Required]
    public string EmailAddress { get; set; }

    [Required]
    public string Password { get; set; }

    // "M" for mail, "F" for female.
    [Required]
    public string Gender { get; set; }

    [Required]
    public DateTime BirthDate { get; set; }

    public string About { get; set; }

    // 0: Unselected, 1: Primary school,
    // 2: High school 3: University
    [Required]
    public int Education { get; set; }

    //true: Active, false: Passive
    [Required]
    public bool IsActive { get; set; }

    [Required]
    public DateTime RecordDate { get; set; }

    public Person()
    {
        RecordDate = DateTime.Now;
        Password = "123";
        About = "";
    }
}

The [Required] attributes are not related to jTable as you probably know. They are used by ASP.NET MVC and Entity framework for validation.

City is a simple class. It is designed to show the combobox feature of jTable (as you've seen above).

public class City
{
    public int CityId { get; set; }

    [Required]
    public string CityName { get; set; }
}

Controller

jTable always uses the POST method while making AJAX calls to the server and expects a JSON object. URLs (Controller/Action names in ASP.NET MVC) can be arbitrary and they are set while creating a jTable instance (we will see this soon).

Getting the list

You must supply an action to jTable to get a list of records:

[HttpPost]
public JsonResult PersonList()
{
    try
    {
        List<Person> persons = _personRepository.GetAllPersons();
        return Json(new { Result = "OK", Records = persons });
    }
    catch (Exception ex)
    {
        return Json(new { Result = "ERROR", Message = ex.Message });
    }
}

All methods must return a JSON object. Result property must be "OK" if operation is successful. If an error occurs, Message property will contain an error message to show to the user. If Result is "OK", the Records property will contain an array of records to show in the table.

You could pass some parameters to the action that can be used to get records based on some filters. Also, you can paginate or sort the table. We will see this later.

Creating

Creating a record is optional (we will see soon). If you allow user to create a record, you must supply an action to jTable to create a new record:

[HttpPost]
public JsonResult CreatePerson(Person person)
{
    try
    {
        if (!ModelState.IsValid)
        {
            return Json(new { Result = "ERROR", 
              Message = "Form is not valid! " + 
              "Please correct it and try again." });
        }

        var addedPerson = _personRepository.AddPerson(person);
        return Json(new { Result = "OK", Record = addedPerson });
    }
    catch (Exception ex)
    {
        return Json(new { Result = "ERROR", Message = ex.Message });
    }
}

CreatePerson method must return the newly created object as the Record property. This is needed since newly inserted record will has a key (PersonId in this sample) and automatically generated values (such as RecordDate here).

Updating

Editing a record is optional (we will see soon). If you allow user to edit a record, you must supply an action to jTable to update a record:

[HttpPost]
public JsonResult UpdatePerson(Person person)
{
    try
    {
        if (!ModelState.IsValid)
        {
            return Json(new { Result = "ERROR", 
              Message = "Form is not valid! " + 
                "Please correct it and try again." });
        }

        _personRepository.UpdatePerson(person);
        return Json(new { Result = "OK" });
    }
    catch (Exception ex)
    {
        return Json(new { Result = "ERROR", Message = ex.Message });
    }
}

Deleting

Deleting a record is optional (we will see soon). If you allow user to delete a record, You must supply an action to jTable to delete a record:

[HttpPost]
public JsonResult DeletePerson(int personId)
{
    try
    {
        _personRepository.DeletePerson(personId);
        return Json(new { Result = "OK" });
    }
    catch (Exception ex)
    {
        return Json(new { Result = "ERROR", Message = ex.Message });
    }
}

Getting options

jTable can automatically download and fill comboboxes from a URL. For instance, the City combobox in the Person create/edit form above uses this feature. In such cases, you must supply an action to get the option list:

[HttpPost]
public JsonResult GetCityOptions()
{
    try
    {
        var cities = _personRepository.GetCities().Select(
            c => new { DisplayText = c.CityName, Value = c.CityId });
        return Json(new { Result = "OK", Options = cities });
    }
    catch (Exception ex)
    {
        return Json(new { Result = "ERROR", Message = ex.Message });
    }
}

The returning JSON object must have the Options property. It is an array of objects and every object has two properties: DisplayText and Value.

View

C# codes above was not directly related to jTable and specific to the ASP.NET MVC implementation. View side is completely about jTable. When you download jTable, you will have a folder structure as shown below:

jTable folder structure

jquery.jtable.js file is the main and only JavaScript file which you must include in your project. Other files (CSS and images files) are used for styling the table and forms. We will come back to styling later.

First, we add the jtable_blue.css file (my favourite style :) to the HEAD section of the HTML document (Razor view in ASP.NET MVC3):

<link href="http://www.codeproject.com/Scripts/jtable/themes/standard/blue/jtable_blue.css" 
      rel="stylesheet" type="text/css" />

You can add red or purple style files instead of blue, or you can write your own style file. Then we must add the jquery.jtable.js script file to the page:

<script type="text/javascript" src="http://www.codeproject.com/Scripts/jtable/jquery.jtable.js">
</script>

Note that jTable is dependent on jQuery and jQueryUI (included UI effects). So, you must add those scripts to your page before jTable. If you don't have these libraries, go to http://jqueryui.com/download to download jQueryUI (it includes jQuery).

Finally, we can create the jTable instance like this:

<div id="PersonTable" style="width: 580px; margin: auto;"></div>

<script type="text/javascript">

    $(document).ready(function () {

        //Prepare jtable plugin
        $('#PersonTable').jtable({
            title: 'The Person List',
            actions: {
                listAction: '/Home/PersonList',
                deleteAction: '/Home/DeletePerson',
                updateAction: '/Home/UpdatePerson',
                createAction: '/Home/CreatePerson'
            },
            fields: {
                PersonId: {
                    key: true,
                    create: false,
                    edit: false,
                    list: false
                },
                Name: {
                    title: 'Name',
                    width: '15%'
                },
                EmailAddress: {
                    title: 'Emal address',
                    list: false
                },
                Password: {
                    title: 'User Password',
                    type: 'password',
                    list: false
                },
                Gender: {
                    title: 'Gender',
                    width: '12%',
                    options: { 'M': 'Male', 'F': 'Female' }
                },
                CityId: {
                    title: 'Living city',
                    width: '15%',
                    options: '/Home/GetCityOptions'
                },
                BirthDate: {
                    title: 'Birth date',
                    width: '18%',
                    type: 'date',
                    displayFormat: 'yy-mm-dd'
                },
                Education: {
                    title: 'Education',
                    list: false,
                    type: 'radiobutton',
                    options: { '1': 'Primary school', 
                       '2': 'High school', '3': 'University' }
                },
                About: {
                    title: 'About this person',
                    type: 'textarea',
                    list: false
                },
                IsActive: {
                    title: 'Status',
                    width: '10%',
                    type: 'checkbox',
                    values: { 'false': 'Passive', 'true': 'Active' },
                    defaultValue: 'true'
                },
                RecordDate: {
                    title: 'Record date',
                    width: '18%',
                    type: 'date',
                    displayFormat: 'dd.mm.yy',
                    create: false,
                    edit: false
                }
            }
        });

        //Load person list from server
        $('#PersonTable').jtable('load');
    });

</script>

Yes, it's a long definition but that's all! jTable does not need anything else to create tables, forms, and animations. I'll explain all options in the Details section but I want to explain some basics now.

As you can see, jTable just needs a div container as the only HTML tag. It gets options:

  • title: Title of the table.
  • actions: URLs of actions that are used to create/delete/update/list records.
  • fields: All fields of the record. A field entry has properties that define the field.

Finally, the load method of jTable is used to get records from the server (we will see this in detail). You can always call this method to load/refresh table data from the server.

Paging

jTable allows you server side paging with AJAX. See a demo here. It looks like the sample below:

Paging with jTable

To enable paging, paging option must set to true. You can also set pageSize option (default value is 10).

$('#PersonTable').jtable({
    //...
    paging: true, //Set paging enabled
    actions: {
        //...
    },
    fields: {
        //...
    }
});

If paging is enabled, jTable sends two query string parameters to the server on listAction AJAX call:

  • jtStartIndex: Start index of records for current page.
  • jtPageSize: Count of maximum expected records.

Also, one additional information is expected from server:

  • TotalRecordCount: Total count of records (not only this page).

An ASP.NET MVC action that is used for paging is shown below:

[HttpPost]
public JsonResult PersonList(int jtStartIndex, int jtPageSize)
{
    try
    {
        int personCount = _personRepository.GetPersonCount();
        List<Person> persons = _personRepository.GetPersons(jtStartIndex, jtPageSize);
        return Json(new { Result = "OK", Records = persons, TotalRecordCount = personCount });
    }
    catch (Exception ex)
    {
        return Json(new { Result = "ERROR", Message = ex.Message });
    }
}

Sorting

jTable allows you server side sorting with AJAX. See a demo here. It looks like the sample below:

jTable sorting

To enable sorting, sorting option must set to true. You can also set defaultSorting option. It can be a field name of a column of the table. For instance, if you want table sorted by Name by default, defaultSorting can be 'Name ASC' or 'Name DESC'.

$('#PersonTable').jtable({
    //...
    sorting: true, //Enable sorting
    defaultSorting: 'Name ASC', //Sort by Name by default
    actions: {
        //...
    },
    fields: {
        //...
    }
});

If sorting is enabled, jTable sends a query string parameter to the server on listAction AJAX call:

  • jtSorting: A string represents requested sorting. It is built from sorting field name plus sorting direction. For instance, It can be 'Name ASC', 'BirtDate DESC', 'Age ASC'... etc.

An ASP.NET MVC action that is used for sorting is shown below:

[HttpPost]
public JsonResult PersonList(int jtStartIndex = 0, int jtPageSize = 0, string jtSorting = null)
{
    try
    {
        int personCount = _personRepository.GetPersonCount();
        List<person> persons = _personRepository.GetPersons(jtStartIndex, jtPageSize, jtSorting);
        return Json(new { Result = "OK", Records = persons, TotalRecordCount = personCount });
    }
    catch (Exception ex)
    {
        return Json(new { Result = "ERROR", Message = ex.Message });
    }
} 

Note that while sorting can be used with paging (as in this sample), it is completely independed from paging.

Selecting

jTable allows you client side selecting rows. See a demo here. It looks like the sample below:

jTable selecting

To enable selecting, selecting option must set to true. You can set multiselect option to true to allow user to select multiple rows at once. You can set selectingCheckboxes option to true to show checkboxes as the sample above. Finally, you can set selectOnRowClick to false to prevent row selecting on clicking anywhere on the row (it's true as default).

To get list of selected rows, you can call selectedRows method of jTable anytime (see sample usage). Also, you can get notified when selection changed by selectionChanged event.

//Prepare jtable plugin
$('#PersonTable').jtable({
    //...
    selecting: true, //Enable selecting
    multiselect: true, //Allow multiple selecting
    selectingCheckboxes: true, //Show checkboxes on first column
    //selectOnRowClick: false, //Enable this to only select using checkboxes
    actions: {
        //...
    },
    fields: {
        //...
    },
    //Register to selectionChanged event
    selectionChanged: function () {
        //Get all selected rows
        var $selectedRows = $('#PersonTable').jtable('selectedRows');

        $('#SelectedRowList').empty();
        if ($selectedRows.length > 0) {
            //Show selected rows
            $selectedRows.each(function () {
                var record = $(this).data('record');
                $('#SelectedRowList').append(
                    'PersonId: ' + record.PersonId +
                    'Name:' + record.Name
                    );
            });
        } else {
            //No rows selected
            $('#SelectedRowList').append('No row selected! Select rows to see here...');
        }
    }
});

In the sample above, we are registering to selectionChanged event. In the event handler, we are getting selected rows by selectedRows method. It returns a jQuery selection, so we can call any jQuery method on it. We can get the record by record data property. Then we can get fields of record as record.Name, record.PersonId... etc.

Master/Child tables

jTable supports unlimited level of child tables for a table. Child tables can also have their children and so on... A child table is releated in a row in master table. Look at the screen below:

Master Child table on jTable

Click here to see a live demo. When you click phone icon at left of a row, a new table slides down below the clicked row and you can manipulate phones of the selected person. You can do everything just as a regular jTable. When you click close button, child table slides up and closed.

To implement a child table, first we must understand custom (computed) column support of jTable. Green phone icon on the figure above is created in a custom column. To create a custom column, we use display option of jtable field definition as like below:

//...
Phones: {
    title: '',
    width: '3%',
    sorting: false,
    edit: false,
    create: false,
    display: function (personData) {
        var $img = $('<img src="http://www.codeproject.com/Content/images/Misc/phone.png" title="Edit phone numbers" />');
        return $img;
    }
}
//...

Phones is a field definition as Name or Gender columns. But Person record has not a field named Phones. So, we define a function that will create value of this field to show on the table. display function is used for that. It is called by jTable for each row. It must return a text, HTML code or jQuery object. In the sample above, I created an image (green phone icon) as a jQuery object and returned it. Then jTable showed this image in the row. personData argument (you can change name of the argument of course) has record property that can be used to get record values for current row. So, if you want to use Name of the person, you can get it using personData.record.Name.

So far so good. But, how to open child table when user clicks this image. jTable defines two methods: openChildTable and closeChildTable to control child tables. So, web can open a child table when user clicks the phone icon (in the display method above):

$img.click(function() {
    $('#PersonTable').jtable('openChildTable',
        $img.closest('tr'),
        {
            title: personData.record.Name + ' - Phone numbers',
            actions: {
                listAction: '/PagingPerson/PhoneList?PersonId=' +
                            personData.record.PersonId,
                deleteAction: '/PagingPerson/DeletePhone',
                updateAction: '/PagingPerson/UpdatePhone',
                createAction: '/PagingPerson/CreatePhone'
            },
            fields: {
                StudentId: {
                    type: 'hidden',
                    defaultValue: studentData.record.StudentId
                },
                PhoneId: {
                    key: true,
                    create: false,
                    edit: false,
                    list: false
                },
                PhoneType: {
                    title: 'Phone type',
                    width: '30%',
                    options: { '1': 'Home phone', 
                               '2': 'Office phone', 
                               '3': 'Cell phone'}
                },
                Number: {
                    title: 'Phone Number',
                    width: '30%'
                },
                RecordDate: {
                    title: 'Record date',
                    width: '20%',
                    type: 'date',
                    displayFormat: 'dd.mm.yy',
                    create: false,
                    edit: false
                }
            }
        }, function(data) { //opened handler
            data.childTable.jtable('load');
        });
});

openChildTable has three parameters. First one is used to indicate the row which is used as master row of child table. Here, I got container tr element of the image, so it gives the current row. Second parameter is a regular jTable initialization options. You can pass any option that can be passed to any jTable instance. So, you can define a custom column and open a second level child. Third and the last parameter is a callback method that is called by jTable after child table successfully created and opened. Here, I loaded records after child table is opened.

Look at the listAction. It's something like that: '/PagingPerson/PhoneList?PersonId=' + personData.record.PersonId. Thus, we are getting phone numbers those are related to current person (personData comes from display method, see codes above). Also, we need PersonId in the server side while creating a new phone number for a person. It's done with a hidden field (See StudentId definition). Given default value is used for new records.

When you create a child table, jTable automatically closes it when user clicks close icon of the table. You can change/override these functionalities. See details to learn in deep.

ASP.NET Web Forms support

jTable has direct support for ASP.NET Web Forms Page Methods since jTable v1.4.1. While jTable is already platform independed, I have built an extension to jTable to support Page Methods in most proper way. For instance, see the code below. This page method is used to get student list as paged and sorted. It's pretty much similar to it's MVC version.

[WebMethod(EnableSession = true)]
public static object StudentList(int jtStartIndex, int jtPageSize, string jtSorting)
{
    try
    {
        //Get data from database
        int studentCount = Repository.StudentRepository.GetStudentCount();
        List<student> students = Repository.StudentRepository.GetStudents(jtStartIndex, jtPageSize, jtSorting);
 
        //Return result to jTable
        return new { Result = "OK", Records = students, TotalRecordCount = studentCount };
    }
    catch (Exception ex)
    {
        return new { Result = "ERROR", Message = ex.Message };
    }
}

For more information on ASP.NET Web Forms support, see the tutorial in jTable.org. Also, the download file in this article includes samples in ASP.NET Web Forms.

Details

Now I will explain detailed usage of jTable.

Methods

jTable defines fallowing methods:

load(postData, completeCallback)

Loads records from the server. All parameters are optional. If you want to pass some parameters to the server, you can pass them in the postData argument while calling the load method, like this:

$('#PersonTable').jtable('load', { CityId: 2, Name: 'Halil' });

You can get people who are living in city 2 and whose name is Halil like shown above. Surely, you must handle these parameters in the server side. Also, you can pass a callback method as completeCallback, that is called when loading of data is successfully completed.

reload(completeCallback)

Re-loads records from server with last postData. This method can be used to refresh table data from server since it does not change current page, sorting and uses last postData (passed on last load call). Also, you can pass a callback method as completeCallback, that is called when loading of data is successfully completed.

selectedRows()

Gets all selected rows as jQuery selection. See the sample above.

deleteRows(rows)

Deletes given rows from server and table. rows parameter must be a jQuery selection. This method can be combined with selectedRows method. Thus, you can get selected rows and pass to deleteRows method to delete them.

openChildTable(row, tableOptions, opened)

This method is used to create and open a child table for a data row (See Master/Child section above). rowargument is a data row on the table, tableOptions are standard jTable options that is used to initialize child table. opened is a callback that is called by jTable when the child table is shown (After opening animation is finished).

closeChildTable(row, closed)

This method is used to close an open child table for a table row. row is a jQuery row object (tr element) on the table. closed is a callback function that is called when child table is closed.

openChildRow(row)

This method is used to open child row for a table row. Child rows generally used to show child tables. If you want to show child tables, you don't need to use this method, use openChildTable method instead. If you want to open a custom child row, use this method. It returns the opened child row. Thus, you can fill it with a custom content. A child row is related to a specific data row in the table (which is passed as row agrument). If the data row is removed from table, it's child is also automatically removed.

closeChildRow(row)

This method is used to close an open child row for a table row. See openChildRow method. (This method is internally used by jTable to close child tables.)

getChildRow(row)

This method is used to get child row (tr element) for a table row. Thus, you can add content to the child row. See openChildRow method.

isChildRowOpen(row)

This method returns true if child row is open for specified row. See openChildRow method.

addRecord(options), removeRecord(options), updateRecord(options)

These methods are used to manipulate table data programmatically. Since they have a bit detailed usage, please see reference documentation for these methods.

Actions

There are four main actions that are used by jTable to perform AJAX requests to the server:

  • listAction: A URL address to get the list of records.
  • createAction: A URL address to submit a create new record form.
  • updateAction: A URL address to submit an edit record form.
  • deleteAction: A URL address to delete a record.

If you don't want to use an action, just don't define it. For instance, if you don't want to allow user to delete a row, don't supply a deleteAction URL. Thus, jTable will not put a delete button for the records.

ASP.NET MVC3 Razor With jQuery For Beginners

Posted by imomins on June 5, 2012 at 10:05 AM Comments comments (0)

Table of content

Introduction

In this article you will find the simplest way to create your first ASP.NET MVC application. This is a tutorial for absolute beginners to ASP.NET MVC. The only prerequisite for following this tutorial is that you know how to use Visual Studio, and understand HTML and C# syntax. Also, I will show you briefly how you can use some jQuery plug-ins so it would be helpful if you know some jQuery syntax. If you are not familiar with jQuery, it is not a problem, you can just skip those parts because they are optional enhancements.

Background

What is MVC (Model-View-Controller)? MVC is a simple architecture where all components are separated into three classes:

  1. Model - Classes that contain data that will be shown to the user.
  2. View - Components that will display the model to the user.
  3. Controller - Components that will handle any interaction with the user.

In the web framework, the user will enter some URL to the ASP.NET MVC application, and the controller, model, and view will handle this request and return the HTML back to the user. The interaction between the browser and the server that has model, view, and controller components is shown in the following figure:

This simple scenario of processing an MVC request is described in the following steps:

  1. The user enters in the browser some URL that is sent to the server, e.g., http://localhost/Product/List.
  2. The user request is analyzed by the framework in order to determine what controller should be called.
  3. The Controller takes the parameters that the user has sent, calls the model to fetch some data, and loads the model object that should be displayed.
  4. The Controller passes the model object to the view.
  5. The View gets data from the model, puts it into the HTML template, and sends the response back to the user browser.
  6. The browser shows the HTML that is received from the server.

In this example, I will show how you can create a simple application that allows you to list and manage user details using ASP.NET MVC using the Razor syntax.

First, what is Razor? When you create a view component that translates C# data objects to HTML view, you can use several template syntax. Razor is one nice and clean syntax for combining C# and HTML code. In the following listing, you can see a simple example of the Razor syntax:

@{
 string name = "Jovan";
 var dateOfBirth = new { Day = 8, Month = 12, Year = 1980 }; 
 string[] skills = new string[] { "MVC",  "C#", "JQuery", "ASP.NET" };
}

<h2>@name</h2>
<p>Born in year: @dateOfBirth.Year</p>
<ul>
@foreach(skill in skills){
 <li>skill</li> 
}
</ul>

In the first part, I have defined a few C# variables, and then I have injected them into the HTML code. The resulting HTML output is shown in the following listing:

<h2>Jovan</h2>
<p>Born in year: 1980</p>
<ul>
 <li>MVC</li>
 <li>C#</li>
 <li>JQuery</li>
 <li>ASP.NET</li>
</ul>

As you can see, C# code will be discarded and only values from that code will be injected in the HTML template. Putting C# data into HTML with Razor syntax is easy - just put the name of the C# variable with the @ prefix. This works both with simple types and object fields. Even if you have more complex processing such as outputting the list of elements with some loop, the syntax is very clean.

If you are not familiar with Razor, you can see a quick reference here or a full reference on the ASP.NET MVC site.

Note that in this example, C# data is defined directly in the view. However, in the real code, C# data will come from the model that is provided by the controller (see figure above).

Using the code

To start with this code, you will need to have Visual Studio or at least Web Developer. If you do not have it, you can install it from the ASP.NET MVC site. There you can find all the necessary prerequisites for installing the MVC framework.

Once you install Web Developer, creating an MVC application is easy. Just go to File/New Project, select ASP.NET MVC Web Application, and the wizard will walk you through the setup process.

Here you should put the name of your project and determine where it will be placed. You can use the default settings if you want. The following sections will explain the structure and elements of the created MVC project.

MVC Project structure

When you create your MVC web application, it will be organized in the following folders:

  • Model containing your model classes.
  • Controller where are placed classes named as <CONTROLLER-NAME>Controller. These classes contain the action method that will be called when an HTTP request is sent.
  • Views - In this folder are placed template files that will be used to generate HTML as a response. Views are partitioned into subfolders. Each controller has its own subfolder named the same way as the controller where the controller's views are placed.
  • CSS files and images will be placed in the Content folder.
  • JavaScript files will be placed in the Scripts folders.

An example of that kind of structure is shown in the following figure:

In this figure, you can see all the components described above. We have two controllers User and School and their views in the /Views/School and /Views/User folders. Views that are placed in the /Views/Shared folder are shared among all controllers and views. Note that views have a .cshtml file extension. This means that they are using Razor syntax for view templates (this syntax is used in this tutorial).

Model

Model can be any class that defines a data structure that will be shown to the user. It can be a plain C# class, an Entity Framework model generated from a database, even a DataSet (although it is not recommended to use it in MVC). In this example, I will use a plain list of objects as a simulation of the data repository. The examples in this article will display a table of users from the list, show/edit details of a user object from the list, and enable you to add/delete users from the list. The Model class used in the application is shown in the following listing:

public partial class User
{
    public int UserID { get; set; }
    public string Name { get; set; }
    public string Address { get; set; }
    public string Town { get; set; }
    public string County { get; set; }
    public string Country { get; set; }
    public string Email { get; set; }
    public DateTime DoB { get; set; }
    public bool IsActive { get; set; }
    public string UserName { get; set; }
    public string Password { get; set; }
    public int Rating { get; set; }
}

This example will not use persistent data storage (e.g., database). I will put the User object in a plain list and the application will use it to show user data. An example of that kind of "repository" is shown in the following example:

public class UserRepository
{
        public static List<User> Users = new List<User>();
}

Although I will not explain any advanced data access techniques, I will use some simple LINQ queries to find user data from the list. The following listing shows LINQ queries that find users:

var user = userList.First(x => x.UserID == id); 
var bestUsers = userList.Where(x => x.Rating > 8);

The first line of code finds the first object in the user list that has property UserID equal to the ID variable (i.e., finds a user by ID). The second line finds all the users with rating greater than 8.

The form parameter => expression is an inline function (lambda expression) that is used to define the criterion for finding users from the list. It is just a shorter version for the inline function that would look like:

function(parameter){ return expression; }

You can find more information about LINQ queries in the Using LINQ Queries article.

View

View is a plain file that defines a template that will be used to show Model data. In the simplest scenario, you can imagine View as a plain HTML code where are placed positions where you will inject Model properties. An example of that kind of View is shown in the following listing:

<fieldset>
    <legend>User</legend>
    <div class="display-label">Name</div>
    <div class="display-field">@Model.Name</div>
    <div class="display-label">Address</div>
    <div class="display-field">@Model.Address</div>
</fieldset>

In this Ciew is defined an HTML structure that will be shown to the user, and the places where the Model data will be placed. The example will inject the Model Name and Address properties into the HTML code. The syntax @Model.<<PropertyName>> defines a place where the Model property will be placed in the View. If you have values "Jane Smith" for name and "Regent street 12, London" for address, the following HTML output will be generated:

<fieldset>
    <legend>User</legend>
    <div class="display-label">Name</div>
    <div class="display-field">Jane Smith</div>
    <div class="display-label">Address</div>
    <div class="display-field">Regent street 12, London</div>
</fieldset>

When you generate complex form elements such as INPUT, TEXTAREA, etc., you can use the same approach as the one in the previous example. You can put HTML code for INPUT and inject some property of the Model directly in the value attribute. An example is shown in the following listing:

<input name="address" id="address"  value="@Model.Address" class="medium-size" />

However, instead of plain HTML, you can use a number of built-in Extension Methods of the HTML class.

@Html.TextBox( "address", Model.Address)
@Html.TextBoxFor(  model => model.Address )

The first parameter is the name/ID for the textbox, and the second parameter specifies the value it should have. This helper method will render an INPUT tag and the type="text" attribute. In the second example is used the TextBoxFor method where is passed a lambda expression that specifies the Address property. In this case we do not need to explicitly specify name/id of the input field - the helper method will take it from the property name. There are other helper methods that can be used to generate other form elements:

  • Html.DropDownListFor()
  • Html.CheckboxFor()
  • Html.RadioButtonFor()
  • Html.ListBoxFor()
  • Html.PasswordFor()
  • Html.HiddenFor()
  • Html.LabelFor()

You can also add your own methods that render some of your custom HTML such as Html.Table(), Html.Calendar(), etc. You can see more details in Creating custom helpers on the MVC site. You can also generate HTML without specifying the type using the Html.DisplayFor and Html.EditorFor methods. An example is shown in the following listing:

@Html.DisplayFor( model => model.Address )
@Html.EditorFor(  model => model.Address )

In these methods, we have not specified the type of input at all, because it will be determined based on the type of the property that should be shown. As an example, if the type of the property is string, EditorFor will generate text input. A more interesting example is when you pass some object to EditorFor. By default, the EditorFor method will generate an INPUT element for each property in the object based on the type (e.g., text input for string, checkbox for boolean, etc.). DisplayFor will do the same except that it will render non-editable markup. You can find more details about the display templates here. However, the true power of these methods can be seen when you create custom templates for object types. This is a more advanced topic but if you are interested in this, you can see this article for more details.

Now back to basics - how do we add a new View? In the folder structure above, you can see the Views folder and the subfolders called User, School, Shared, etc. Just right-click on the folder where you want to put the View, go to Add New View, and the following dialog will be shown to you:

Here you can enter the name of the View (usually it is the same as the name of the controller action) and the type of the Model object that will be shown. Also, you can add an empty View and start coding it, or you can select some of the predefined templates for list, details, edit, create, or delete.

You can imagine Views as separate pages that will be shown to the user. However, there are a few other types of Views (described below).

Layout page

When you are creating a set of pages, probably you will need to use the same elements on many pages. As an example, all pages will have the same menu, the same CSS/JavaScript files included etc. In ASP.NET MVC, you do not need to copy the same elements on each page. You can use the so-called layout pages where a general layout of the entire MVC application will be defined and used on each View page. An example of a layout page that will be used in this project is shown in the following listing:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>This is a title of the page</title>
    <link href="/Content/Site.css" rel="stylesheet" type="text/css" />
    <script src="/Scripts/jquery-1.5.1.min.js" type="text/javascript"></script>
    <script src="/Scripts/modernizr-1.7.min.js" type="text/javascript"></script>
    @RenderSection("PageScripts",false)
</head>

<body>
    @RenderBody()
</body>
</html>

As you can see, in the layout page, I have included all the necessary CSS/JavaScript files that will be used across all pages. Also, I have defined two custom placeholders where each View will put specific content. These two placeholders are:

  1. Section PageScripts - where each page will be able to put some JavaScript or CSS files that will be required only on that page.
  2. RenderBody statement that defines where the content of a particular View will be injected in the general layout.

Partial views

Another way to organize and reuse your View code is to put elements that are used on several Ciews into separate files. These are not standalone Views that are shown to the user - these are only partial views that are included on other main View pages.

Partial Views are HTML templates as regular Vviews. An example of a partial view that shows the current date is shown in the following listing:

_CurrentDateView.cshtml
<div class="now">Current date is @DateTime.Now.ToString()</div>

Whenever you need to include this partial view, you can just call it by name as shown in the following example:

@Html.Partial("_CurrentDateView")

In the place of the call, the entire content of the View will be included. You can put this statement in standard views, layout pages, and even in other partial views.

Controller

Controller is the heart of the processing logic in MVC model. When a URL is sent to an internet application in the format /<<Controller>>/<<Action>>/<<Parameter>> (e.g., /User/Details/1), it will be parsed and the class called <<Controller>>Controller (e.g., UserController) will be found, the method <<Action>> in that controller will be called (e.g., method Details in the above URL), and the parameter will be passed to that method. The Controller will perform all the necessary processing - it will find a Model and pass it to the View.

The Controller can have any public method with arbitrary parameters that will be passed. As an example, the following listing shows the Controller called ExampleController with a method ControllerAction that receives three parameters - id, name, and flag.

public ExampleController
{
        public ActionResult ControllerAction(int id, string name, bool flag)
    {
        var model = GetModel(id, name, flag);
        return View(model);
    }
}

You can call this Controller's action using the following URL:

/Example/ControllerAction?id=17&name=test&flag=true

This is the default mapping between URL routes and controller/actions where the first word in the URL represents a controller name, and the second one is the action method name. However, you can modify it and add your own routing mapping rules. You can see more details about the custom routing in the Creating custom routes article.

The Controller will automatically map parameters from the request to the method arguments by name. This is useful if you have a form with many parameters that can be automatically read from the request and the user in the action method body.

How you can add a new Controller? It is similar to adding new Views - go to the Controller folder, right-click, and add a new Controller. The following dialog will be shown:

Here you can enter the name of the Controller - note that it must be in the format <<Name>>Controller. Also, you can choose one of the predefined templates - empty controller, controller with list, details, edit, create, and delete actions, and controller that is already connected to the database via Entity Framework. In this example, I have started with an empty controller. Once you create an empty controller, you can add action methods in the following format:

public MyController{
    [Get]
    public ActionResult MyAction()
    {
        return View();
    }
}

The action method should return a view that will display the HTML in the browser (ActionResult type in the example above). By default if you add the MyAction method in the MyController class, it will be called when the /My/MyAction URL is sent. You can change this behavior, but it will not be described in this beginner level article. Also, you might notice the [Get] attribute that is placed before the method. This attribute tells the action that it should react only to a GET HTTP protocol. As an alternative, I could set [Post] instead of [Get] or I could leave it blank so the action would be opened on both GET and POST protocols.

Also, you must have noticed that the last statement in the action is return View(). If an action MyAction is placed in MyController, this statement will find the MyAction.cshtml View in the My folder in the Ciews section. This is the default rule for returning Views in action methods. If you do not want to use this default view, you can choose what View should be returned by specifying the View name, e.g.,

return View(name);

Note that you have an easy way to go to the View, or to add a View for a particular action. Just right click on the action and you will see a context menu that will enable you to add a View for this action. Add View action will open the "Add View" dialog as in the previous section. If a View with the same name as an action already exists, "Go to view" will open the view page.

jQuery

Although it is not a direct part of MVC, jQuery is a very useful JavaScript library that can enable you to enhance your user interface. The first useful thing you will be able to do is easily find HTML elements in the HTML. Some of the simplest queries are shown in the following table:

jQuery selector Description
$("table")Find all table nodes in the HTML
$("#Name")Find elements in the HTML with ID Name
$(".required")Find all elements in the HTML that have CSS class "required"
$("table a.delete") In any table, find all A tags that have CSS class "delete"
$("table tr:odd") Find all odd rows in the table

Once you find elements with jQuery selectors, you can hide them, change their color, attributes (classes, values, inner text), add some event handlers to them (click, double click), etc. An example of the code that attaches a click handler to the link is shown in the following listing:

$('a').click(function (event) {

    // prevent default action (going to the another page)
    event.preventDefault()

    // Do something
});

Also, jQuery contains a set of useful plug-ins that enable you to enhance your UI elements. Some examples are shown in the following table:

Plug-inDescription
$("input.calendar").datepicker() Add date picker (calendar) dialog on each input element that has CSS class "calendar"
$("form").validate() Add JavaScript validation on the form
$("table").dataTable()Add JavaScript sorting, pagination, and filtering in the table

You can fine more details and tutorials about jQuery on the jQuery documentation site. There is also an interesting article "jQuery for beginners" where you can find some interesting examples. This is optional, but very easy and useful to add in the MVC application. Note that when you create an MVC application, jQuery will be automatically included in the project. However, plug-ins are not part of core jQuery that is included in the MVC project so you will need to find them and put them in your project manually.

How can you use this JavaScript code? First, you will need to include the jQuery library from the jQuery download page. In your MVC project, you will probably find this library included in the scripts folder so you can just add a reference to this script in the layout page. Then you will be able to use this library - an example is shown in the following listing:

<script src="/Scripts/jquery-1.7.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
    $(document).ready(function () {
        $("table").fadeOut("slow");
    }
</script>

In this example, I have included jQuery version 1.7.1. and added a fade out effect on the table element. Note that this statement is placed in the document ready wrapper. Using this wrapper, any JavaScript code within it will be called when an entire document is loaded and ready to be processed. This is a common practice in jQuery programming. Here I have added jQuery code as an inline script, but you can put it into a separate file.

Creating your first MVC application

In this section, I will show how you can create a simple MVC application that lists, edits, creates, and deletes users.

List/Index page

On the list page will be displayed a table with a list of users in the repository. The page will be opened when the /User/Index URL is called. Therefore, we would need to create an Index method and place it in the UserController class. An example of the Index method is shown in the following listing:

public ActionResult Index()
{
    var model = UserRepository.Users;
    return View(model);
}

This method is fairly simple. It takes a list of users from the repository and passes it to the View. The list view takes this list and displays a table as shown in the following listing:

<table class="display">
    <thead>
    <tr>
        <th>
            Name
        </th>
        <th>
            Address
        </th>
        <th>
            Town
        </th>
        <th>
            County
        </th>
        <th>
            Rating
        </th>
        <th></th>
    </tr>
    </thead>
    <tbody>

@foreach (var item in Model) {
    <tr>
        <td>
            @item.Name
        </td>
        <td>
            @item.Address
        </td>
        <td>
            @item.Town
        </td>
        <td>
            @item.County
        </td>
        <td>
            @item.Rating
        </td>
        <td>
            <a href="/User/Details/@item.UserID">Details</a> |
            <a href="/User/Edit/@item.UserID">Edit</a> |
            <a href="/User/Delete/@item.UserID" class="delete">Delete</a>
        </td>
    </tr>
}
</tbody>
</table>

As you can see, this list view has taken a collection of user objects and outputs them as an HTML table in the foreach loop. Note that you do not need to create an HTML wrapper with head and body tags. These are defined in the layout page, and this part of the HTML code is just injected in the middle of the page (the RenderBody statement in the layout page above). An example of the list page is shown in the following figure:

Applying the jQuery DataTables plug-in

The table you saw is just a plain table without any functionality. However you can easily enhance this table with the jQuery JavaScript library to add some advanced features such as sorting, pagination, filtering, etc. In the layout page, you saw that I have put a PageScripts placeholder that allows each view to put some custom JavaScript or CSS. In this example, only on the list page, I will add some JavaScript that will enhance this table. An example of this additional script is shown in the following listing:

@section PageScripts{
    <link href="/Content/dataTable/demo_table.css" rel="stylesheet" type="text/css" />
    <script src="/Scripts/jquery.dataTables.1.8.2.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $("table").dataTable();
        }
    </script>
}

This script has included jQuery DataTables CSS and JavaScript files, and applied DataTables function on the HTML table. As a result, you will convert this plain table to a feature-rich table shown on the following figure:

I will not explain how this jQuery plug-in can be used in more detail, but if you are interested, you can take a look at the Enhancing HTML tables using the jQuery DataTables plug-in article.

Details page

On the details page will be shown information of a particular user by ID. The request that is sent to the server-side is in the following format:

/User/Details/123

In this request, you can see that UserController will be called, and that the Details method with parameter 123 will be executed. 123 is the ID of the record that will be shown. The Details method will take the ID of the user, find this user in the model repository, and pass it to the view:

public ActionResult Details(int id)
{
    var model = UserRepository.Users.First(user => user.UserID == id);
    return View(model);
}

The View is also simple - it receives the user model object and injects user properties into the view. Part of view is shown in the following listing:

@model JQueryMVC.Models.User

<h2>User Details</h2>
<fieldset>
    

Rss_feed