Image preview before uploading using AsynFileUpload
|
|
comments (0)
|
It is always nice to show the preview of the image which has to be uploaded by the user.
After lot of searching I found that the HTML upload i.e input type="file"... is not useful as it does not expose enough server side events. For this scenario the better control is Ajax control ToolKit's AjaxFileUpload, which has enough server side events and client side events.
After the file is uploaded instead of saving it in the location in the server instead HttpHandler can be used which can write the uploaded image directly into the response. so no storage and less headaches.
What have been done.
1) Use AjaxFileUpload to upload the file.
2) Store the file in the session object.
3) Use the session object in the Handler. Set the Image control source to the Handler.
In .aspx.cs
public static readonly string STORED_IMAGE = "SessionImage";
protected void OnAsyncFileUploadComplete(object sender, AsyncFileUploadEventArgs e)
{
if (asyncFileUpload.PostedFile != null)
{
HttpPostedFile file = asyncFileUpload.PostedFile;
byte[] data = ReadFile(file);
//Store the image in the session.
Session[STORED_IMAGE] = data;
}
}
private byte[] ReadFile(HttpPostedFile file)
{
byte[] data = new Byte[file.ContentLength];
file.InputStream.Read(data, 0, file.ContentLength);
return data;
}
In .aspx
Note: Use the randomnumber in the querystring of the handler otherwise, browser caches the first image and returns the same image again and again.
<script language="javascript" type="text/javascript">
function getRandomNumber() {
var randomnumber = Math.random(10000);
return randomnumber;
}
function OnClientAsyncFileUploadComplete(sender, args)
{
var handlerPage = '<%= Page.ResolveClientUrl("~/ImageHandler.ashx")%>';
var queryString = '?randomno=' + getRandomNumber();
var src = handlerPage + queryString;
var clientId = '<%=previewImage.ClientID %>';
document.getElementById(clientId).setAttribute("src", src);
}
</script>
The Handler
Note use the IRequiresSessionState to access the session variables in the Handler.
public class ImageRequestHandler: IHttpHandler, IRequiresSessionState
{
public void ProcessRequest(HttpContext context)
{
context.Response.Clear();
if(context.Request.QueryString.Count != 0)
{
//Get the stored image and write in the response.
var storedImage = context.Session[_Default.STORED_IMAGE] as byte[];
if (storedImage != null)
{
Image image = GetImage(storedImage);
if (image != null)
{
context.Response.ContentType = "image/jpeg";
image.Save(context.Response.OutputStream, ImageFormat.Jpeg);
}
}
}
}
private Image GetImage(byte[] storedImage)
{
var stream = new MemoryStream(storedImage);
return Image.FromStream(stream);
}
public bool IsReusable
{
get { return false; }
}
}
In web.config
<add validate="false" verb="*" path="ImageHandler.ashx"type="ImagePreviewDemo.ImageRequestHandler,ImagePreviewDemo"/>
Please find the full source code attached.
Attachments
Did you like this resource? Share it with your friends and show your love!
Simple .NET MVC 3 web application with integrated Facebook OAuth API
|
|
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
|
|
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
- Put Security Check keywords.
- Click on Submit.
- Fill basic information about app.
- 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.
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();Source Code
01.using System;02.using Facebook;03.public partial class Facebook_ConnectFacebook : System.Web.UI.Page04.{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. else36. {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.}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.
- Click on Save changes.
- now Facebook app has created.
- 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.
- Click on facebook banner.
- It will ask Request for Permission. Click Allow.
- It will show all basic information of user on webpage.
- 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.
AJAX based CRUD tables using ASP.NET MVC 3 and jTable jQuery plug-in
|
|
comments (0)
|

A full-featured jTable instance. Try a live demo here.
Contents
- Introduction to the problem
- What is jTable?
- Live demo
- A sample page with ASP.NET MVC 3 and jTable
- Paging
- Sorting
- Selecting
- Master/child tables
- ASP.NET Web Forms support
- Details
- Combining with validation
- Future works
- More
- History
- References
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:

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:

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:

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:

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:

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:

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:

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:

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:

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:

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:

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:

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
|
|
comments (0)
|
Table of content
- Introduction
- Background
- Using the code
- Creating your first MVC application
- Advanced topics
- Conclusion
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:
- Model - Classes that contain data that will be shown to the user.
- View - Components that will display the model to the user.
- 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:
- The user enters in the browser some URL that is sent to the server, e.g., http://localhost/Product/List.
- The user request is analyzed by the framework in order to determine what controller should be called.
- 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.
- The Controller passes the model object to the view.
- The View gets data from the model, puts it into the HTML template, and sends the response back to the user browser.
- 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:
- Section
PageScripts- where each page will be able to put some JavaScript or CSS files that will be required only on that page. RenderBodystatement 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:
<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-in | Description |
$("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>
Introduction to ASP.NET Web Programming Using the Razor Syntax (C#)
|
|
comments (1)
|
Introduction to ASP.NET Web Programming Using the Razor Syntax (C#) OverviewTutorialsVideosSamplesForumBooksOpen Source
Introducing ASP.NET Web Pages 2 - Getting StartedIntroducing ASP.NET Web Pages 2 - Programming BasicsIntroducing ASP.NET Web Pages 2 - Displaying DataIntroducing ASP.NET Web Pages 2 - HTML Form BasicsIntroducing ASP.NET Web Pages 2 - Entering Database Data by Using FormsIntroducing ASP.NET Web Pages 2 - Updating Database DataIntroducing ASP.NET Web Pages 2 - Deleting Database DataIntroducing ASP.NET Web Pages 2 - Creating a Consistent LayoutIntroducing ASP.NET Web Pages 2 - Publishing a Site by Using WebMatrixIntro to ASP.NET Web Programming Razor SyntaxASP.NET Web Pages Visual BasicIntro to DebuggingWorking with FormsValidating User Input in ASP.NET Web Pages SitesCreating a Consistent LookCustomizing Site-Wide BehaviorCreating and Using a Helper in an ASP.NET Web Pages SiteRendering ASP.NET Web Pages Sites for Mobile DevicesCreating Readable URLs in ASP.NET Web Pages SitesWorking with DataDisplaying Data in a ChartMigrating a Database to SQL ServerWorking with FilesWorking with ImagesWorking with VideoDisplaying Maps in an ASP.NET Web Pages SiteAdding Security and MembershipAdding Security to Any SiteEnabling Login from External Sites in an ASP.NET Web Pages SiteUsing a CAPTCHA to Prevent Automated Programs (Bots) from Using Your ASP.NET Web SiteSending Email from Your SiteAdding Search to Your Web SiteAdding Social Networking to Your WebsiteCaching to Improve the Performance of Your WebsiteAnalyzing Traffic
This article gives you an overview of programming with ASP.NET Web Pages using the Razor syntax. ASP.NET is Microsoft's technology for running dynamic web pages on web servers. This articles focuses on using the C# programming language.
What you'll learn:
- The top 8 programming tips for getting started with programming ASP.NET Web Pages using Razor syntax.
- Basic programming concepts you'll need.
- What ASP.NET server code and the Razor syntax is all about.
The Top 8 Programming Tips
This section lists a few tips that you absolutely need to know as you start writing ASP.NET server code using the Razor syntax.
Note The Razor syntax is based on the C# programming language, and that's the language that's used most often with ASP.NET Web Pages. However, the Razor syntax also supports the Visual Basic language, and everything you see you can also do in Visual Basic. For details, see the appendix Visual Basic Language and Syntax.
You can find more details about most of these programming techniques later in the article.
1. You add code to a page using the @ character
The @ character starts inline expressions, single statement blocks,
and multi-statement blocks:
<!-- Single statement blocks -->
@{ var total = 7; }
@{ var myMessage = "Hello World"; }
<!-- Inline expressions -->
<p>The value of your account is: @total </p>
<p>The value of myMessage is: @myMessage</p>
<!-- Multi-statement block -->
@{
var greeting = "Welcome to our site!";
var weekDay = DateTime.Now.DayOfWeek;
var greetingMessage = greeting + " Today is: " + weekDay;
}
<p>The greeting is: @greetingMessage</p>
This is what these statements look like when the page runs in a browser:

2. You enclose code blocks in braces
A code block includes one or more code statements and is enclosed in braces.
<!-- Single statement block. -->
@{ var theMonth = DateTime.Now.Month; }
<p>The numeric value of the current month: @theMonth</p>
<!-- Multi-statement block. -->
@{
var outsideTemp = 79;
var weatherMessage = "Hello, it is " + outsideTemp + " degrees.";
}
<p>Today's weather: @weatherMessage</p>
The result displayed in a browser:

3. Inside a block, you end each code statement with a semicolon
Inside a code block, each complete code statement must end with a semicolon. Inline expressions don't end with a semicolon.
<!-- Single-statement block -->
@{ var theMonth = DateTime.Now.Month; }
<!-- Multi-statement block -->
@{
var outsideTemp = 79;
var weatherMessage = "Hello, it is " + outsideTemp + " degrees.";
}
<!-- Inline expression, so no semicolon -->
<p>Today's weather: @weatherMessage</p>
4. You use variables to store values
You can store values in a variable,
including strings, numbers, and dates, etc. You create a new variable using the
var keyword. You can insert variable values directly in a page using @.
<!-- Storing a string -->
@{ var welcomeMessage = "Welcome, new members!"; }
<p>@welcomeMessage</p>
<!-- Storing a date -->
@{ var year = DateTime.Now.Year; }
<!-- Displaying a variable -->
<p>Welcome to our new members who joined in @year!</p>
The result displayed in a browser:

5. You enclose literal string values in double quotation marks
A string is a sequence of characters that are treated as text. To specify a string, you enclose it in double quotation marks:
@{ var myString = "This is a string literal"; }
If the string that you want to display contains a backslash character (\) or double quotation marks
( " ;), use
a verbatim string literal
that's prefixed with the @ operator. (In C#, the \ character has special
meaning unless you use a verbatim string literal.)
<!-- Embedding a backslash in a string -->
@{ var myFilePath = @"C:\MyFolder\"; }
<p>The path is: @myFilePath</p>
To embed double quotation marks, use a verbatim string literal and repeat the quotation marks:
<!-- Embedding double quotation marks in a string -->
@{ var myQuote = @"The person said: ""Hello, today is Monday."""; }
<p>@myQuote</p>
Here's the result of using both of these examples in a page:

Note Notice that the @ character is used both to
mark verbatim string literals in C# and to mark code in ASP.NET pages.
6. Code is case sensitive
In C#, keywords (like var, true, and if) and variable names are case sensitive.
The following lines of code create two different variables, lastName
and LastName.
@{
var lastName = "Smith";
var LastName = "Jones";
}
If you declare a variable as var lastName = "Smith"; and if you
try to reference that variable in your page as @LastName, an error
results because LastName won't be recognized.
Note In Visual Basic, keywords and variables are not case sensitive.
7. Much of your coding involves objects
An object represents a thing that you can program with — a page, a text box, a
file, an image, a web request, an email message, a customer record (database row),
etc. Objects have properties that describe their characteristics and that you
can read or change — a text box object
has a Text property (among others), a request object has a Url property, an email
message has a From property, and a customer object has a FirstName property. Objects
also have methods that are the "verbs" they can perform. Examples include a file
object's Save method, an image object's Rotate method, and an email object's
Send
method.
You'll often work with the Request object, which gives you information like the
values of text boxes (form fields) on the page, what type of browser made
the request, the URL of the page, the user identity, etc. The following example shows how
to access properties of the Request object and how to call the
MapPath method of
the Request object, which gives you the absolute path of the page on the server:
<table border="1">
<tr>
<td>Requested URL</td>
<td>Relative Path</td>
<td>Full Path</td>
<td>HTTP Request Type</td>
</tr>
<tr>
<td>@Request.Url</td>
<td>@Request.FilePath</td>
<td>@Request.MapPath(Request.FilePath)</td>
<td>@Request.RequestType</td>
</tr>
</table>
The result displayed in a browser:

8. You can write code that makes decisions
A key feature of dynamic web pages is that you can determine what to do based
on conditions. The most common way to do this is with the if statement
(and optional else statement).
@{
var result = "";
if(IsPost)
{
result = "This page was posted using the Submit button.";
}
else
{
result = "This was the first request for this page.";
}
}
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form method="POST" action="" >
<input type="Submit" name="Submit" value="Submit"/>
<p>@result</p>
</form>
</body>
</html>
</body>
</html>
The statement if(IsPost) is a shorthand way of writing if(IsPost == true).
Along with if statements, there are a variety of ways to test conditions,
repeat blocks of code, and so on, which are described later in this article.
The result displayed in a browser (after clicking Submit):

A Simple Code Example
This procedure shows you how to create a page that illustrates basic programming techniques. In the example, you create a page that lets users enter two numbers, then it adds them and displays the result.
- In your editor, create a new file and name it AddNumbers.cshtml.
- Copy the following code and markup into the page, replacing anything already
in the page.
@{
var total = 0;
var totalMessage = "";
if(IsPost) {
// Retrieve the numbers that the user entered.
var num1 = Request["text1"];
var num2 = Request["text2"];
// Convert the entered strings into integers numbers and add.
total = num1.AsInt() + num2.AsInt();
totalMessage = "Total = " + total;
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>Add Numbers</title>
<meta charset="utf-8" />
<style type="text/css">
body {background-color: beige; font-family: Verdana, Arial;
margin: 50px; }
form {padding: 10px; border-style: solid; width: 250px;}
</style>
</head>
<body>
<p>Enter two whole numbers and then click <strong>Add</strong>.</p>
<form action="" method="post">
<p><label for="text1">First Number:</label>
<input type="text" name="text1" />
</p>
<p><label for="text2">Second Number:</label>
<input type="text" name="text2" />
</p>
<p><input type="submit" value="Add" /></p>
</form>
<p>@totalMessage</p>
</body>
</html>Here are some things for you to note:
The
@character starts the first block of code in the page, and it precedes thetotalMessagevariable that's embedded near the bottom of the page.The block at the top of the page is enclosed in braces.
In the block at the top, all lines end with a semicolon.
The variables
total,num1,num2, andtotalMessagestore several numbers and a string.The literal string value assigned to the
totalMessagevariable is in double quotation marks.Because the code is case-sensitive, when the
totalMessagevariable is used near the bottom of the page, its name must match the variable at the top exactly.The expression
num1.AsInt() + num2.AsInt()shows how to work with objects and methods. TheAsIntmethod on each variable converts the string entered by a user to a number (an integer) so that you can perform arithmetic on it.The
<form>tag includes amethod="post"attribute. This specifies that when the user clicks Add, the page will be sent to the server using the HTTP POST method. When the page is submitted, theif(IsPost)test evaluates to true and the conditional code runs, displaying the result of adding the numbers.
- Save the page and run it in a browser. (Make sure the page is selected
in the Files workspace before you run it.) Enter two whole numbers and then
click the Add button.
Basic Programming Concepts
This article provides you with an overview of ASP.NET web programming. It isn't an exhaustive examination, just a quick tour through the programming concepts you'll use most often. Even so, it covers almost everything you'll need to get started with ASP.NET Web Pages.
But first, a little technical background.
The Razor Syntax, Server Code, and ASP.NET
Razor syntax is a simple programming syntax for embedding server-based code in a web page. In a web page that uses the Razor syntax, there are two kinds of content: client content and server code. Client content is the stuff you're used to in web pages: HTML markup (elements), style information such as CSS, maybe some client script such as JavaScript, and plain text.
Razor syntax lets you add server code to this client content. If there's server code in the page, the server runs that code first, before it sends the page to the browser. By running on the server, the code can perform tasks that can be a lot more complex to do using client content alone, like accessing server-based databases. Most importantly, server code can dynamically create client content — it can generate HTML markup or other content on the fly and then send it to the browser along with any static HTML that the page might contain. From the browser's perspective, client content that's generated by your server code is no different than any other client content. As you've already seen, the server code that's required is quite simple.
ASP.NET web pages that include the Razor syntax have a special file extension (.cshtml or .vbhtml). The server recognizes these extensions, runs the code that's marked with Razor syntax, and then sends the page to the browser.
Where does ASP.NET fit in?
Razor syntax is based on a technology from Microsoft called ASP.NET, which in turn is based on the Microsoft .NET Framework. The.NET Framework is a big, comprehensive programming framework from Microsoft for developing virtually any type of computer application. ASP.NET is the part of the .NET Framework that's specifically designed for creating web applications. Developers have used ASP.NET to create many of the largest and highest-traffic websites in the world. (Any time you see the file-name extension .aspx as part of the URL in a site, you'll know that the site was written using ASP.NET.)
The Razor syntax gives you all the power of ASP.NET, but using a simplified syntax that's easier to learn if you're a beginner and that makes you more productive if you're an expert. Even though this syntax is simple to use, its family relationship to ASP.NET and the .NET Framework means that as your websites become more sophisticated, you have the power of the larger frameworks available to you.

Basic Syntax
Earlier you saw a basic example of how to create an ASP.NET Web Pages page, and how you can add server code to HTML markup. Here you'll learn the basics of writing ASP.NET server code using the Razor syntax — that is, the programming language rules.
If you're experienced with programming (especially if you've used C, C++, C#, Visual Basic, or JavaScript), much of what you read here will be familiar. You'll probably need to familiarize yourself only with how server code is added to markup in .cshtml files.
Combining Text, Markup, and Code in Code Blocks
In server code blocks, you often want to output text or markup (or both) to the page. If a server code block contains text that's not code and that instead should be rendered as is, ASP.NET needs to be able to distinguish that text from code. There are several ways to do this.
- Enclose the text in an HTML element like
<p></p>or<em></em>:
@if(IsPost) {
// This line has all content between matched <p> tags.
<p>Hello, the time is @DateTime.Now and this page is a postback!</p>
} else {
// All content between matched tags, followed by server code.
<p>Hello <em>stranger</em>, today is: <br /> </p> @DateTime.Now
}The HTML element can include text, additional HTML elements, and server-code expressions. When ASP.NET sees the opening HTML tag (for example,
<p>), it renders everything including the element and its content as is to the browser, resolving server-code expressions as it goes. - Use the
@:operator or the<text>element. The@:outputs a single line of content containing plain text or unmatched HTML tags; the<text>element encloses multiple lines to output. These options are useful when you don't want to render an HTML element as part of the output.
@if(IsPost) {
// Plain text followed by an unmatched HTML tag and server code.
@: The time is: <br /> @DateTime.Now
<br/>
// Server code and then plain text, matched tags, and more text.
@DateTime.Now @:is the <em>current</em> time.
}If you want to output multiple lines of text or unmatched HTML tags, you can precede each line with
@:, or you can enclose the line in a<text>element. Like the@:operator,<text>tags are used by ASP.NET to identify text content and are never rendered in the page output.@if(IsPost) {
// Repeat the previous example, but use <text> tags.
<text>
The time is: <br /> @DateTime.Now
<br/>
@DateTime.Now is the <em>current</em> time.
</text>
}
@{
var minTemp = 75;
<text>It is the month of @DateTime.Now.ToString("MMMM"), and
it's a <em>great</em> day! <br /><p>You can go swimming if it's at
least @minTemp degrees. </p></text>
}The first example repeats the previous example but uses a single pair of
<text>tags to enclose the text to render. In the second example, the<text>and</text>tags enclose three lines, all of which have some uncontained text and unmatched HTML tags (<br />), along with server code and matched HTML tags. Again, you could also precede each line individually with the@:operator; either way works.Note When you output text as shown in this section — using an HTML element, the
@:operator, or the<text>element — ASP.NET doesn't HTML-encode the output. (As noted earlier, ASP.NET does encode the output of server code expressions and server code blocks that are preceded by@, except in the special cases noted in this section.)
Whitespace
Extra spaces in a statement (and outside of a string literal) don't affect the statement:
@{ var lastName = "Smith"; }
A line break in a statement has no effect on the statement, and you can wrap statements for readability. The following statements are the same:
@{ var theName =
"Smith"; }
@{
var
personName
=
"Smith"
;
}
However, you can't wrap a line in the middle of a string literal. The following example doesn't work:
@{ var test = "This is a long
string"; } // Does not work!
To combine a long string that wraps to multiple lines like the above code, there
are two options. You can use the concatenation operator (+), which you'll see later
in this article. You can also use the @ character to create a verbatim string literal,
as you saw earlier in this article. You can break verbatim string literals across
lines:
@{ var longString = @"This is a
long
string";
}
Code (and Markup) Comments
Comments let you leave notes for yourself or others. They also allow you to disable (comment out) a section of code or markup that you don't want to run but want to keep in your page for the time being.
There's different commenting syntax for Razor code and for HTML markup. As with all Razor code, Razor comments are processed (and then removed) on the server before the page is sent to the browser. Therefore, the Razor commenting syntax lets you put comments into the code (or even into the markup) that you can see when you edit the file, but that users don't see, even in the page source.
For ASP.NET Razor comments, you start the comment with @* and
end it with *@. The comment can be
on one line or multiple lines:
@* A one-line code comment. *@
@*
This is a multiline code comment.
It can continue for any number of lines.
*@
Here is a comment within a code block:
@{
@* This is a comment. *@
var theVar = 17;
}
Here is the same block of code, with the line of code commented out so that it won't run:
@{
@* This is a comment. *@
@* var theVar = 17; *@
}
Inside a code block, as an alternative to using Razor comment syntax, you can use the commenting syntax of the programming language you're using, such as C#:
@{
// This is a comment.
var myVar = 17;
/* This is a multi-line comment
that uses C# commenting syntax. */
}
In C#, single-line comments are preceded by the // characters,
and multi-line comments begin with /*
and end with */. (As with Razor comments, C# comments are not
rendered to the browser.)
For markup, as you probably know, you can create an HTML comment:
<!-- This is a comment. -->
HTML comments start with <!-- characters and
end with -->. You can use HTML comments to surround not only
text, but also any HTML markup that you may want to keep in the page
but don't want to render. This HTML comment will hide the entire content of the tags and the text they
contain:
<!-- <p>This is my paragraph.</p> -->
Unlike Razor comments, HTML comments are rendered to the page and the user can see them by viewing the page source.
Variables
A variable is a named object that you use to store data. You can name variables anything, but the name must begin with an alphabetic character and it cannot contain whitespace or reserved characters.
Variables and Data Types
A variable can have a specific data type, which indicates what kind of data is stored in the variable. You can have string variables that store string values (like "Hello world"), integer variables that store whole-number values (like 3 or 79), and date variables that store date values in a variety of formats (like 4/12/2012 or March 2009). And there are many other data types you can use.
However, you generally don't have to specify a type for a variable. Most of the time, ASP.NET can figure out the type based on how the data in the variable is being used. (Occasionally you must specify a type; you'll see examples where this is true.)
You declare a variable using the var keyword (if you don't want to specify a
type) or by using the name of the type:
@{
// Assigning a string to a variable.
var greeting = "Welcome!";
// Assigning a number to a variable.
var theCount = 3;
// Assigning an expression to a variable.
var monthlyTotal = theCount + 5;
// Assigning a date value to a variable.
var today = DateTime.Today;
// Assigning the current page's URL to a variable.
var myPath = this.Request.Url;
// Declaring variables using explicit data types.
string name = "Joe";
int count = 5;
DateTime tomorrow = DateTime.Now.AddDays(1);
}
The following example shows some typical uses of variables in a web page:
@{
// Embedding the value of a variable into HTML markup.
<p>@greeting, friends!</p>
// Using variables as part of an inline expression.
<p>The predicted annual total is: @( monthlyTotal * 12)</p>
// Displaying the page URL with a variable.
<p>The URL to this page is: @myPath</p>
}
If you combine the previous examples in a page, you see this displayed in a browser:

Converting and Testing Data Types
Although ASP.NET can usually determine a data type automatically, sometimes it can't. Therefore, you might need to help ASP.NET out by performing an explicit conversion. Even if you don't have to convert types, sometimes it's helpful to test to see what type of data you might be working with.
The most common case is that you have to convert a string to another type, such as to an integer or date. The following example shows a typical case where you must convert a string to a number.
@{
var total = 0;
if(IsPost) {
// Retrieve the numbers that the user entered.
var num1 = Request["text1"];
var num2 = Request["text2"];
// Convert the entered strings into integers numbers and add.
total = num1.AsInt() + num2.AsInt();
}
}
As a rule, user input comes to you as strings. Even if you've prompted users to enter a number, and even if they've entered a digit, when user input is submitted and you read it in code, the data is in string format. Therefore, you must convert the string to a number. In the example, if you try to perform arithmetic on the values without converting them, the following error results, because ASP.NET cannot add two strings:
Cannot implicitly convert type 'string' to 'int'.
To convert the values to integers, you call the AsInt method. If the conversion
is successful, you can then add the numbers.
The following table lists some common conversion and test methods for variables.
|
Method |
Description |
Example |
|
|
Converts a string that represents a whole number (like "593") to an integer. |
var myIntNumber = 0; |
|
|
Converts a string like "true" or "false" to a Boolean type. |
var myStringBool = "True"; |
|
|
Converts a string that has a decimal value like "1.3" or "7.439" to a floating-point number. |
var myStringFloat = "41.432895"; |
|
|
Converts a string that has a decimal value like "1.3" or "7.439" to a decimal number. (In ASP.NET, a decimal number is more precise than a floating-point number.) |
var myStringDec = "10317.425"; |
|
|
Converts a string that represents a date and time value to the ASP.NET
|
var myDateString = "12/27/2012"; |
|
|
Converts any other data type to a string. |
int num1 = 17; |
Operators
An operator is a keyword or character that tells ASP.NET what kind of command to perform in an expression. The C# language (and the Razor syntax that's based on it) supports many operators, but you only need to recognize a few to get started. The following table summarizes the most common operators.
|
Operator |
Description |
Examples |
|
|
Math operators used in numerical expressions. |
@(5 + 13)
|
|
|
Assignment. Assigns the value on the right side of a statement to the object on the left side. |
var age = 17; |
|
|
Equality. Returns |
var myNum = 15; |
|
|
Inequality. Returns |
var theNum = 13; |
|
|
Less-than, |
if (2 < 3) { |
|
|
Concatenation, which is used to join strings. ASP.NET knows the difference between this operator and the addition operator based on the data type of the expression. |
// The displayed result is "abcdef". |
|
|
The increment and decrement operators, which add and subtract 1 (respectively) from a variable. |
int theCount = 0; |
|
|
Dot. Used to distinguish objects and their properties and methods. |
var myUrl = Request.Url; |
|
|
Parentheses. Used to group expressions and to pass parameters to methods. |
@(3 + 7)
|
|
|
Brackets. Used for accessing values in arrays or collections. |
var income = Request["AnnualIncome"]; |
|
|
Not. Reverses a |
bool taskCompleted = false; |
|
|
Logical AND and OR, which are used to link conditions together. |
bool myTaskCompleted = false; |
How can a formcollection be enumerated in ASP.NET MVC?
|
|
comments (1)
|
Here are 3 ways to do it specifically with a FormCollection object.
public ActionResult SomeActionMethod(FormCollection formCollection)
{
foreach (var key in formCollection.AllKeys)
{
var value = formCollection[key];
}
foreach (var key in formCollection.Keys)
{
var value = formCollection[key.ToString()];
}
// Using the ValueProvider
var valueProvider = formCollection.ToValueProvider();
foreach (var key in valueProvider.Keys)
{
var value = valueProvider[key];
}
}
ASP.Net Chart Control On Shared Hosting Environment
|
|
comments (0)
|
Chart Control of ASP.Net 3.5 is very handy way to get statictical data as charts. There are variety of ways to display data with Chart Control. Also it is extramely simple to adapt it to your project. But as I hear from so many ASP.Net user nowadays, there might be some problems when it comes to publish it on your web server, especially on shared hosting servers !
After you install the Chart Control, in order to run ASP.Net chart control on your project, you need to configure your web.config file on your root directory which you have already done (I guess !). If you do that properly, you are able to run it on your local server perfectly. But it is not enough for you to be good to go on your web server.
You need to have Chart Control installed on your web server in order to run it on web !
It is easy to do that if you have your own server but for those who have their website files on a shared hosting service, it is a bit hard. But you do not need to beg your hosting provider to make it be installed on server. Only you need to do is to make proper changes on your web.config file and believe me those changes are much more simple than you think ! Of Course, some references is needed to be added to the Bin Folder on your root directory !
Solution :
Follow this directory on windows explorer:
C:\Program Files\Microsoft Chart Controls\Assemblies
You will see 4 DLL files inside the folder. Two of those files are for Windows Applications and two of them for Web Applications. We need web application dll files so copy the dll files which are named 'System.Web.DataVisualization.Design' and 'System.Web.DataVisualization'
Paste those dll files into the Bin folder on the root directory of your Web Application.
Secondly, open the Web.Config file on the root directory of your web application.Find the <appSettings> node. You have a key add inside this just like below;
<add key="ChartImageHandler" value="storage=file;timeout=20;dir=c:\TempImageFiles\;" />
Replace this tag with the new one as below;
<add key="ChartImageHandler" value="storage=file;timeout=20;"/>
Save the changes on your Web.Config file and close it. Now copy the two dll inside the bin folder and replace the Web.Config file on your server with your new Web.Config file.
That's it !
Now you should be able to run the Chart Control on your Web Server without begging your hosting provider
If you have any problem with this, I recommend you to check the following codes if they exist on your Web.Config file or not;
how to create and consume webservice using asp.net
|
|
comments (0)
|
What is Web Service?
Web Service is an application that is designed to interact directly with other applications over the internet. In simple sense, Web Services are means for interacting with objects over the Internet. The Web serivce consumers are able to invoke method calls on remote objects by using SOAP and HTTP over the Web. WebService is language independent and Web Services communicate by using standard web protocols and data formats, such as
HTTP
XML
SOAP
Advantages of Web Service
Web Service messages are formatted as XML, a standard way for communication between two incompatible system. And this message is sent via HTTP, so that they can reach to any machine on the internet without being blocked by firewall.
Examples for Web Service
Weather Reporting: You can use Weather Reporting web service to display weather information in your personal website.
Stock Quote: You can display latest update of Share market with Stock Quote on your web site.
News Headline: You can display latest news update by using News Headline Web Service in your website.
In summary you can any use any web service which is available to use. You can make your own web service and let others use it. Example you can make Free SMS Sending Service with footer with your advertisement, so whosoever use this service indirectly advertise your company... You can apply your ideas in N no. of ways to take advantage of it.
Frequently used word with web services
What is SOAP?
SOAP (simple object access protocol) is a remote function calls that invokes method and execute them on Remote machine and translate the object communication into XML format. In short, SOAP are way by which method calls are translate into XML format and sent via HTTP.
What is WSDL?
WSDL stands for Web Service Description Language, a standard by which a web service can tell clients what messages it accepts and which results it will return.WSDL contains every detail regarding using web service and Method and Properties provided by web service and URLs from which those methods can be accessed and Data Types used.
What is UDDI?
UDDI allows you to find web services by connecting to a directory.
What is Discovery or .Disco Files?
Discovery files are used to group common services together on a web server. Discovery files .Disco and .VsDisco are XML based files that contains link in the form of URLs to resources that provides discovery information for a web service. Disco File contains URL for the WSDL, URL for the documentation and URL to which SOAP messages should be sent.
Before start creating web service first create one table in your database and give name UserInformation in my code I am using same name and enter some dummy data for our testing purpose
Now we will see how to create new web service application in asp.net
Open visual studio ---> Select File ---> New ---> Web Site ---> select ASP.NET Web Service

Now our new web service ready our webservice website like this

Now open your Service.cs file in web service website to write the code to get the user details from database
Before writing the WebMethod in Service.cs first add following namespaces
using System.Xml;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
After adding namespaces write the following method GetUserDetails in Service.cs page
ASP.NEt Interview Question
|
|
comments (1)
|
1. Explain the life cycle of an ASP .NET page.?
Following are the events occur during ASP.NET Page Life Cycle:
1)Page_PreInit
2)Page_Init
3)Page_InitComplete
4)Page_PreLoad
5)Page_Load
6)Control Events
7)Page_LoadComplete
8)Page_PreRender
9)SaveViewState
10)Page_Render
11)Page_Unload
Among above events Page_Render is the only event which is raised by page. So we can't write code for this event.
2. how does the cookies work in asp.net?
we know Http is an state-less protocol which is required for interaction between clinet and server .
so there is an need to remeber state of request raised by an web browser so that
web server can recognize you have already previously visited or not.
There are two types of state management techniques:
a) Client side state management
b) Server - side statemanagement
Using cookies comes under clinet side statemanagement .In HttpResponse we write
Cookie containing sessionId and other information within it.
when a browser made a request to the web server the same cookie is sent to the server where server recognize the session id and get other information stored to it previously.
3. What is Ispostback method in ASP.Net? Why do we use that??
Basically Post back is an action performed by a interactive Webpage. When it goes to the server side for a non-client Operation Server again posts it back to the client and hence the name.
Ex:
if(!IsPostBack)
will not allow the page to post back again n again bcoz it reduces the performance.
5. what is the difference between application state and caching?
Application Object and Cached Object both falls under Server side State Management.
Application object resides in InProc i.e. on the same server where we hosted our application.
Cache Object resides on server side/ DownStream/Client Side.
Application Object will be disposed once application will stop.
Cache Object can be disposed using Time based cache dependency.
Only one user can access Application Object at a time hence we have to lock it every time we modify it.
6. what is boxing and unboxing?
Boxing is what happens when a value-type object is assigned to a reference-type variable.
Unboxing is what happens when a reference-type variable is assigned to a value-type variable.
7. What are the uses of Reflection??
Reflection is a concept using which we can
1) Load assemblies dynamically
2) Invoke methods at runtime
3) Retriving type information at runtime.
8. What is the use of AutoWireup in asp.net?
AutoEventWireup attribute is used to set whether the events needs to be automatically generated or not.
In the case where AutoEventWireup attribute is set to false (by default) event handlers are automatically required for Page_Load or Page_Init. However when we set the value of the AutoEventWireup attribute to true the ASP.NET runtime does not require events to specify event handlers like Page_Load or Page_Init.
9. what events will occur when a page is loaded?
Below are the events occures during page load.
1) Page_PreInit
2) Page_Init
3) Page_InitComplete
4) Page_PreLoad
10. Where is the View state Data stored?
ViewState data is stored in the hidden field. When the page is submitted to the server the data is sent to the server in the form of hidden fields for each control. If th viewstate of the control is enable true the value is retained on the post back to the client when the page is post backed.
12. Where do the Cookie State and Session State information be stored?
Cookie Information will be stored in a txt file on client system under a
folder named Cookies. Search for it in your system you will find it. Coming to Session State
As we know for every process some default space will be allocated by OS.
In case of InProc Session Info will be stored inside the process where our
application is running.
In case of StateServer Session Info will be stored using ASP.NET State Service.
In case of SQLServer Session info will be stored inside Database. Default DB
which will be created after running InstallSQLState Script is ASPState.
14. What are the different types of sessions in ASP.Net? Name them.?
Session Management can be achieved in two ways
1)InProc
2)OutProc
OutProc is again two types
1)State Server
2)SQL Server
InProc
Adv.:
1) Faster as session resides in the same process as the application
2) No need to serialize the data DisAdv.:
1) Will degrade the performance of the application if large chunk of data is stored
2) On restart of IIS all the Session info will be lost
State Server
Adv.:
1) Faster then SQL Server session management
2) Safer then InProc. As IIS restart
won't effect the session data
DisAdv.:
1) Data need to be serialized
2) On restart of ASP.NET State Service session info will be lost
3)Slower as compared to InProc
SQL Server
Adv.:
1) Reliable and Durable
2) IIS and ASP.NET State Service
restart won't effect the session data
3) Good place for storing large chunk of data
DisAdv.:
1) Data need to be serialized
2) Slower as compare to InProc and State Server
3)Need to purchase Licensed
version of SQL Serve
16. What is caching? What are different ways of caching in ASP.NET?
Caching is a technique of persisting the data in memory for immediate access to requesting program calls. This is considered as the best way to enhance the performance of the application.
Caching is of 3 types:
Output Caching - Caches the whole page.
Fragment Caching - Caches a part of the page
Data Caching - Caches the data
17. What is meant by 3-tier architecture.
We generally split our application into 3-Layers
1)Presentation Layer ( Where we keep all web forms Master Pages and User Controls).
2)Business Layer (Where we keep business logic). e.g Code related to manipulating data Custom Exception classes Custom Control classes Login related code if any etc. etc.
3)Data Access Layer (Where we keep code used to interact with DB). e.g. We can have the methods which are using SQL Helper (Application Block).
19. What is the difference between mechine.config and web.config?
machine.config is a system level configuration i.e it is applied on all application in o/s that the configuration is set where as in web.config it is applicable to only one application i.e each asp.net webapplication will contain atleast on web.config file.
21. What is the difference between Response.Redirect and Server.Transfer.
Server.Transfer transfers page processing from one page directly to the next page without making a round-trip back to the client's browser. This provides a faster response with a little less overhead on the server.Server.Transfer does not update the clients url history list or current url.
Response.Redirect is used toredirect the user's browser to another page or site. This performs a trip back to the client where the client's browser is redirected to the new page. The user's browser history list is updated to reflect the new address.
25. What is the exact purpose of http handlers?
ASP.NET maps HTTP requests to HttpHandlers. Each HttpHandler enables processing of individual HTTP URLs or groups of URL extensions within an application. HttpHandlers have the same functionality as ISAPI extensions with a much simpler programming model
Ex
1.Default HttpHandler for all ASP.NET pages ->ASP.NET Page Handler (*.aspx)
2.Default HttpHandler for all ASP.NET service pages->ASP.NET Service Handler (*.asmx)
An HttpHandler can be either synchronous or asynchronous. A synchronous handler does not return until it finishes processing the HTTP request for which it is called. An asynchronous handler usually launches a process that can be lengthy and returns before that process finishes
After writing and compiling the code to implement an HttpHandler you must register the handler using your application's Web.config file.