Wednesday, November 11, 2009

How to filter Exceptions (Such as null parameter) in MVC?

Override your OnException in your controller:
protected override void OnException(ExceptionContext filterContext)
{
if (IsNullParamter(filterContext.Exception))
filterContext.HttpContext.Response.Redirect("~/Home/Index");
base.OnException(filterContext);
}

private bool IsNullParamter(System.Exception ex)
{
string error = ex.Message;
if (error.Contains("System.ArgumentException: The parameters dictionary contains a null entry for parameter")) return true;
if (error.Contains("The parameters dictionary contains a null entry for parameter")) return true;
return false;
}

Tuesday, October 13, 2009

Wednesday, September 16, 2009

Microsoft AJAX CDN, JQuery lib

Source
http://ajax.microsoft.com/ajax/jquery/jquery-1.3.2.min.js

Friday, September 11, 2009

How to improve the performance of ASP.NET MVC web application

Source

Implementing Caching
Implementing HTTP Compression
Implementing JQuery UI library with Google Hosted Ajax Libraries
By combining scripts and other resources
Deploying production code in release mode
Removing default HTTP modules in ASP.NET
Optimizing URL generation

Friday, August 21, 2009

Using ELMAH with ASP.NET MVC

link

Insert following part after configSections after third steps

<elmah>
<security allowRemoteAccess="yes" />
<errorLog type="Elmah.XmlFileErrorLog, Elmah" logPath="~/App_Data" />
<errorMail
from="aaa@aaa.aa"
to="aaa@aaa.aa"
subject="ICM Exception ..."
async="true"
smtpPort="25"
smtpServer="0.0.0.0"
userName=""
password="" />
</elmah>

Test Credit Card Account Numbers

Visa 4111111111111111
Link

Thursday, August 6, 2009

Action Filter in MVC to solve problem of Authentication Timeout

Add an Action Filter in MVC to solve problem of Authentication Timeout. Once Authentication Timeout then redirect to another place.
public class AuthenticationTimeoutFilterAttribute : ActionFilterAttribute
{
public override void OnActionExecuting( ActionExecutingContext filterContext ) {
HttpContext context = HttpContext.Current;
if (!context.User.Identity.IsAuthenticated)
{
context.Response.Redirect("~/ControllerName/ActionName");
}
base.OnActionExecuting ( filterContext );
}
}


Forms Authentication timeout default in ASP.NET 2.0

Wednesday, August 5, 2009

ASP.NET MVC Roadmap

ASP.NET MVC Roadmap
This is a high level roadmap for ASP.NET MVC featuring the areas we are investigating. We will continually update this as we post releases to the CodePlex site.
ASP.NET MVC 2
Theme: Improved Productivity and Enterprise Ready

Developing applications with ASP.NET MVC 2 is going to be more productive than with ASP.NET MVC 1.0 with the improvements being made in this version such as the Templated and Paging Helpers. Additionally, those working with ASP.NET MVC 2 in the enterprise will find that some of the unique needs of their environment will be addressed via the new Areas and AsyncController features.

Runtime
ASP.NET MVC 2 will take a runtime dependency on ASP.NET 3.5 SP1 as we plan to ship project templates and tooling for both Visual Studio 2008 and Visual Studio 2010.

Visual Studio 2010
Visual Studio 2010 Beta 1 support as an add-on (Sometime in June)
ASP.NET MVC 2 Preview 2 included in Visual Studio 2010 Beta 2
ASP.NET MVC 2 RTM included with Visual Studio 2010 RTM

Visual Studio 2008
Will continue to ship a standalone ASP.NET MVC 2 installer for Visual Studio 2008 with SP1
ASP.NET MVC 2 Features
Preview 1 - Early August
Templated Helpers - allow you to automatically associate edit and display elements with data types. For example, a date picker UI element can be automatically rendered every time data of type System.DateTime is used. This is similar to Field Templates in ASP.NET Dynamic Data.
Areas - provide a means of dividing a large web application into multiple projects, each of which can be developed in relative isolation. This helps developers manage the complexity of building a large application by providing a way to group related controllers and views.
Support for Data Annotations - Data Annotations enable attaching validation logic in a central location via metadata attributes applied directly to a model class. First introduced in ASP.NET Dynamic Data, these attributes are now integrated into the default model binder and provide a metadata driven means to validating user input.
Preview 2 and beyond
Client Validation - builds on top of the Templated Helpers and Data Annotations work done in Preview 1 to provide client-side validation based on the model's validation attributes. This provides for a more responsive experience for users filling out a form with validation.
Strongly-typed input helpers – allow generating form input fields using code expressions against the model. This allows the helpers to take advantage of Data Annotations attributes applied to the model and reduces errors caused by lack of strong typing such as typos.
Strongly-typed link helpers – allow developers to take advantage of Intellisense support (due to the strong typing) to discover which controllers and actions are available for linking.
Asynchronous Controller Actions - provides a programming model for writing actions that can call external resources without blocking a thread. This can increase the scalability of a site that needs to interact with web services and other external services.
Areas - continued refining of the Areas feature, enabling a single project approach for developers who wish to organize their application without requiring multiple projects.
Other Improvements - continue to fix known issues carried over from ASP.NET MVC 1.0 as well as ASP.NET MVC 2 Preview 1. Also including API improvements based on user feedback along with minor new features.

Tuesday, August 4, 2009

Microsoft Delivers ASP.NET MVC V2 Preview

Link

Microsoft releases a preview of Version 2 of its ASP.NET MVC Web application development system.

In a blog post on the release, Scott Guthrie, corporate vice president of Microsoft .NET Developer Platform, said the new ASP.NET MVC V2 preview works with .NET 3.5 Service Pack 1 and Visual Studio 2008, and "can be installed side-by-side on the same machine as ASP.NET MVC 1.0."

.....
ASP.NET MVC 2 includes support for a new feature called "areas" that Guthrie said enables developers to "more easily partition and group functionality across an MVC application."

Guthrie said:

Areas provide a means of grouping controllers and views to allow building subsections of a large application in relative isolation [from] other sections. Each area can be implemented as a separate ASP.NET MVC project which can then be referenced by the main application. This helps manage the complexity when building a large application and facilitates multiple teams working ... on a single application together.

In addition, "ASP.NET MVC 2 now includes built-in support for the DataAnnotation validation support that first shipped with .NET 3.5 SP1—and which is used with ASP.NET Dynamic Data and .NET RIA Services," Guthrie said. "DataAnnotations provides an easy way to declaratively add validation rules to Model and ViewModel classes within an application, and have automatic binding and UI helper validation support within ASP.NET MVC."

Moreover, Guthrie said, "In a future ASP.NET MVC 2 preview we are planning to ship the jQuery Validation plug-in as part of the default project template, and add support for the automatic client-side JavaScript enforcement of DataAnnotation validation rules as well. This will enable developers to easily add validation rules in one place on either a Model or ViewModel object, and have them be enforced both client- and server-side everywhere it is used within the application."

Also, ASP.NET MVC V2 includes new HTML user interface helpers that enable developers to "use strong-typed lambda expressions when referencing the view template's model object," Guthrie said in the post. "This enables better compile-time checking of views (so that bugs can be found at build-time as opposed to run-time), and also enables better code IntelliSense support within view templates."

Friday, July 24, 2009

Tuesday, July 21, 2009

Three ways to Use .NET 3.5 Features and C# 3.0 Syntax in .NET 2.0?

Source

Referencing LinqBridge
Referencing System.Core
Implementing features yourself

Monday, July 20, 2009

What is new in Visual Studio 2010 and the .Net Framework 4.0

jQuery - In 2010 major changes has been done for high performance and standard javascript standards compliant JavaScript IntelliSense engine. Microsoft and Jquery group working together to make developer life easy, so Visual Studio 2010 will be the first version of Visual Studio to ship JQuery as a native part of the ASP.NET solution

MVC - All features of "Preview release of ASP.NET MVC" included in Visual Studio 2010
2010 make very easy to build Model-View-Controller aka MVC sites.
n Visual Studio 2010 we deliver the next generation of ASP.NET web tools that make it easy for developers to use TDD to build Model-View-Controller (MVC) based web sites. Wizard based interface to creating views, generating test project for MVC solution. Various templates are given.

Thursday, July 9, 2009

Saturday, June 27, 2009

Summary of interfaces in 3.5 .NET framework IEnumerable, IQueryable and IList

IEnumerable - supports being used in a foreach statement and that's about it.
IQueryable - supports further filtering, paging, etc. Does not support random access via an indexer. Implements IEnumerable
IList - supports random access via an indexer. does not support further filtering. Implements IEnumerable

Tuesday, June 23, 2009

Ajax survey 2009: jQuery and MS Ajax are almost tied among .NET developers

Source
The most used Ajax/JS library among .NET developers is jQuery, which is used by the 71,4% of the users. Second comes the Ajax Control Toolkit with 58,8%, followed by the core ASP.NET Ajax library, which is used by 44,8%.

Friday, June 19, 2009

Browser type in JQuery with source code

var userAgent = navigator.userAgent.toLowerCase();

// Figure out what browser is being used
jQuery.browser = {
version: (userAgent.match( /.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/ ) || [])[1],
safari: /webkit/.test( userAgent ),
opera: /opera/.test( userAgent ),
msie: /msie/.test( userAgent ) && !/opera/.test( userAgent ),
mozilla: /mozilla/.test( userAgent ) && !/(compatible|webkit)/.test( userAgent )
};


//Syntax: RegExpObject.test(string)

Friday, June 12, 2009

What ASP.NET Developers Should Know About jQuery

Source

........
Use selectors. Think in sets.
In the ASP.NET world, it’s rare to select sets of controls through queries. Instead, we’re accustomed to referencing a single control by its unique ID. Of course this is possible in jQuery too, but its selector engine is far more sophisticated.

Using selectors to identify a set of one or more elements is cleaner and more expressive than the iterative machinations you may be used to in ASP.NET server-side code. Before parsing out an ID or iterating over a group of elements in search of certain ones, be sure that the task isn’t more easily accomplished through a jQuery selector.

Use CSS classes for more than just styling.
Another technique that is counterintuitive at first is the use of CSS classes as flags. Coupled with jQuery’s selector engine, “flag” classes are surprisingly powerful.
............

Friday, June 5, 2009

undefined and null are same in Javascript with sample code

undefined is a global property (variable) with a constant value. Javascript treats undefined as being equal to null.
Sample code
<html>
<body>

<script type="text/javascript">
var test;
if (test==null)
{
alert("null");
}

if (test==undefined)
{
alert("undefined");
}
</script>

</body>
</html>

Thursday, May 28, 2009

Some number in Ajax usage among .NET developers

Source
- the most used web frameworks is pretty obviously WebForms (89%) followed by ASP.NET MVC (38%);
- the most used JavaScript library is jQuery with 76%, followed by Ajax Control Toolkit (58%) and ASP.NET Ajax (48%). And still a good 8% is hand-crafting javascript and ajax calls;
- among the ones using ASP.NET Ajax, the vast majority is using the UpdatePanel control (88%) and 58% is using the ASP.NET Ajax client library and talking directly to Json/XML services.

Tuesday, May 26, 2009

How to deal with disabled Javascript in Browsers in ASP.NET MVC

Add noscript html tag into master page to redirect description page:
<noscript>
<meta http-equiv="refresh" content="5; url=<%= Url.Relative("~/ControllerName/ActionName") %>" />
</noscript>

Monday, May 25, 2009

Cache in MVC ActionFilterAttribute

Source

How to add HTML Attributes into html helper

<%=Html.DropDownList("CategoryID", new {@class="input", style="display:none"})%>

Friday, May 22, 2009

Simplest way to redirect user to maintaining page

Just add an HTML file named “app_offline.htm” to the root directory of your website. Adding this file will clear the server cache. When ASP.NET sees the app_offline.htm file, it will shut-down the app-domain for the application (and not restart it for requests), and instead send back the contents of the app_offline.htm file in response to all new dynamic requests for the application.

The size of the file should be more that 512 bytes to be displayed.

Thursday, May 21, 2009

New for web development in Visual Studio 2010

Source

Dynamic IntelliSense for JavaScript
Snippets for HTML and JavaScript

Tuesday, May 19, 2009

DevHawk - Microsoft, Open Source and ASP.NET MVC

Source
...
Personally, I think Microsoft is making small steps in the right direction when it comes to Open Source. Not only have some high profile Microsoft projects go Open Source like ASP.NET MVC and MEF, but we’ve even started taking baby steps for including external intellectual property. Releasing ASP.NET MVC under Ms-PL is a big deal, but I think including jQuery “in the box” is a much, much bigger deal. It remains to be seen if it’s a one-time-only deal or if it’s a new trend inside Microsoft.
...

Monday, May 11, 2009

Martin Fowler: Any fool can write code that a computer can understand. Good programmers write code that humans can understand

Website

ActionButton with Controller name and Action name in ASP.NET/MVC

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

public static class Action
{
public static string ActionButton(this HtmlHelper helper, string Url, string Text)
{
return GetHtmlBy(Url, Text);
}

public static string ActionButton(this HtmlHelper helper, string ControllerName, string ActionName, string ButtonText)
{
var urlhelper = new UrlHelper(helper.ViewContext.RequestContext);
string virtualpath = string.Format("~/{0}/{1}", ControllerName, ActionName);
string absurl = urlhelper.Content(virtualpath);
return GetHtmlBy(absurl, ButtonText);
}

private static string GetHtmlBy(string Url, string Text)
{
string outputUrl = string.Format(@"
<input type='button' onclick=""javacript: window.location='{1}';"" value='{0}' />", Text, Url);
return outputUrl;
}
}


You can use this ActionButton in aspx file:

<%=Html.ActionButton("ControllerName","ActionName","ButtonText") %>

Thursday, May 7, 2009

Link: ASP.NET 4.0 Webforms Enhancements

Source

More Granular ViewState Control and Webforms Routing

Thursday, April 30, 2009

The Four Pillars of ASP.NET, Web Forms, AJAX, MVC and Dynamic Data.

Source

3. ASP.NET MVC. This pillar is the newest to emerge from Microsoft. In fact, as of this writing, it’s only a couple of weeks old, having been released at Mix09. Some ASP.NET curmudgeons would call this a throwback to the days of ASP “classic” spaghetti code, but for many others--especially the alt.net crowd and transplants from Ruby and Java--this represents the cat’s pajamas on the Microsoft web stack. (Of course, it’s amazing how quickly developers find problems in the latest programmer’s paradise--usually before its release--and I’m sure the MVC aficionados are already looking to the next release.)

The basic idea behind ASP.NET MVC is to separate out the three concerns of the MVC pattern: the model, view, and controller. The model represents the data model, the view is the user interface that presents the data and interacts with the user, and the controller is the command center that takes inputs from the view, pushes and pulls data into/from the model, and decides what to do next. By separating out these concerns (as purely as possible), you improve the ability to create unit tests for your applications and, at least on some level, improve application maintainability. If you are into test driven development, then this is the pillar to hook your horse to.

Wednesday, April 29, 2009

Flexigrid link

http://code.google.com/p/flexigrid/

Lightweight but rich data grid with resizable columns and a scrolling data to match the headers, plus an ability to connect to an xml based data source using Ajax to load the content.

Monday, April 27, 2009

Is ASP.NET MVC a half-baked solution?

Source

Let's be clear, ASP.NET MVC is an improvement over WebForms - and those developers refusing to leverage ASP.NET MVC (or something else) for new projects are simply lazy. WebForms is full of leaky abstraction, really tight coupling, and ridiculous concepts - such as viewstates and postbacks.

Being able to write complex systems more cleanly is a good start, but given where web development stands in general, and other platforms specifically, ASP.NET MVC lags far behind (Perl being the only one I can think of which is worse).

There's little question that a big part of the problem is that this is really a VC stack - there is no thought, no support, and no tools for the Model. When you compare the thousands of lines you'll end up writing for your repository/dal/linq/nhiberate to other MVC stacks (which commonly only require that your models to inherit from 1 class), you're already at a serious productivity disadvantage. But the true impact is actually much worse - you lose any cohesiveness of purpose through the controller and views. There is no way to generate HTML labels from model properties, or client side validation. In frameworks such as Akelos, RoR or Django everything flows outwards from the model which allows those frameworks to provide cohesive and integrated tools, not just HtmlHelpers, ActionResults and Routing (which is all you get from ASP.NET MVC).

You end up having to do a whole lot of plumbing on both sides of your system.

Friday, April 24, 2009

How we do MVC

Source

Like many of the frameworks coming out of Redmond, MVC is not an opinionated framework. Rather, it is a framework that enables you to form your own opinions (good or bad). It’s taken quite a long way, with a very stable result at the end. It’s certainly not perfect, and there are a few directions we’d like to go differently given the chance. In the next few posts, I’ll elaborate with real examples on the big examples here, otherwise, I’d love to have people poke holes in our approach

Thursday, April 23, 2009

You Should Learn MVC (with 3 reasons)

Source

1 – Testability. No – not talking about the TDD variety, just testing in general. If you’re “not a testing person” that’s OK – the rest of the computer science world has embraced the idea that “testing what we build is a pretty good idea”. You don’t really want your clients to catch that silly “InvalidCastException” do ya? There’s LOTS of reasons to want to test – again not TDD – just good old Unit Testing! It’s easy peasy with MVC and this alone should pull you in to at least check it out – along with why testing can save you time and money.

2 – Control over HTML. I’m sure you’ve heard this before – mangled ID’s, non-validating HTML, etc. Why is this important? Because you might want to use client-side programming for something! I won’t bang this gong for too long – but it’s a lot more than “making ViewSource look pretty” – you’re communicating with super-finicky creatures (browsers) that love to argue – being able to smith the markup experience makes you a more valuable developer!

3 – Extensibility. Literally every part of MVC Is pluggable – and in the last 3 apps I wrote (Storefront, Nerddinner, and SubSonic’s MVC Starter) I used my own ViewEngine to save some time and work. I’ve spun up my own ControllerFactory so I can use IoC (which is awesome fun!) Understanding this is the keys to the kingdom for any developer! Have you ever been freaked out because you needed to use Page_PreRender to get something to load into the ControlTree properly so it will show when you need it to? MVC does not lock you into anything – you’re free to do what you want to.

Wednesday, April 22, 2009

Basic Selectors in JQuery

1. By the ID attribute.
If the ID contains special character then you can escape them with backslashes. For example to find a text box with ID txtName you can write the following :

$("#txtName")

Then you can do any operation on the text box like getting the value or changing the css class.

2. By given element name. For example to get all the DIV elements following is the syntax

$("div")

This will find all the DIVs present in the page. You can do any operation after that.


3. By given class name. The following code finds all the elements which have class name 'RedButton'.

$(".RedButton")

Source

jQuery Auto-Complete Text Box with ASP.NET MVC

Great example:
Source

"HTTP Error 500 - Internal server error" mean: you have to fix something in your code

500 errors in the HTTP cycle

Any client (e.g. your Web browser or our CheckUpDown robot) goes through the following cycle when it communicates with your Web server:

Obtain an IP address from the IP name of your site (your site URL without the leading 'http://'). This lookup (conversion of IP name to IP address) is provided by domain name servers (DNSs).
Open an IP socket connection to that IP address.
Write an HTTP data stream through that socket.
Receive an HTTP data stream back from your Web server in response. This data stream contains status codes whose values are determined by the HTTP protocol. Parse this data stream for status codes and other useful information.
This error occurs in the final step above when the client receives an HTTP status code that it recognises as '500'.

Fixing 500 errors - general

This error can only be resolved by fixes to the Web server software. It is not a client-side problem. It is up to the operators of your Web server site to locate and analyse the logs which should give further information about the error.

Tuesday, April 21, 2009

http://blog.objectmentor.com/articles/2009/04/20/is-the-supremacy-of-object-oriented-programming-over

Source

I never expected to see this. When I started my career, Object-Oriented Programming (OOP) was going mainstream. For many problems, it was and still is a natural way to modularize an application. It grew to (mostly) rule the world. Now it seems that the supremacy of objects may be coming to an end, of sorts.

I say this because of recent trends in our industry and my hands-on experience with many enterprise and Internet applications, mostly at client sites. You might be thinking that I’m referring to the mainstream breakout of Functional Programming (FP), which is happening right now. The killer app for FP is concurrency. We’ve all heard that more and more applications must be concurrent these days (which doesn’t necessarily mean multithreaded). When we remove side effects from functions and disallow mutable variables, our concurrency issues largely go away. The success of the Actor model of concurrency, as used to great effect in Erlang, is one example of a functional-style approach. The rise of map-reduce computations is another example of a functional technique going mainstream. A related phenomenon is the emergence of key-value store databases, like BigTable and CouchDB, is a reaction to the overhead of SQL databases, when the performance cost of the Relational Model isn’t justified. These databases are typically managed with functional techniques, like map-reduce.

But actually, I’m thinking of something else. Hybrid languages like Scala, F#, and OCaml have demonstrated that OOP and FP can complement each other. In a given context, they let you use the idioms that make the most sense for your particular needs. For example, immutable “objects” and functional-style pattern matching is a killer combination.

Difference between and

<input type="button" /> buttons will not submit a form -
In Ajax, it is for client side stuff.
They're generally used in conjunction with JavaScript as part of an AJAX application.

<input type="submit"> buttons will submit the form to the serveri side.
UserController/Action will process submitted information

Friday, April 17, 2009

Simplest example for JQuery validation

<html>

<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="http://dev.jquery.com/view/trunk/plugins/validate/jquery.validate.js">
</script>
<script>

$(document).ready(function(){
$("#contactForm").validate();
});
</script>


<body>
<div id="container">
<form id="contactForm" method="" action="">
<label for="cemail">E-Mail</label>
<input id="cemail" name="email" size="25" class="required email" />
<input id="number" name ="number" class="required number"/>
<input class="submit" type="submit" value="submit"/>
</form>
</div>

</body>
</html>

Thursday, April 16, 2009

Boxy/JQuery

Source
Simple stuff only.

JQuery selector and getElementById

Javascript:
document.getElementById('product_id_01')

JQuery selector:
$('#product_id_01')[0]

Wednesday, April 15, 2009

How to debug Javascript/JQuery in VS2008

1. In browser: Enable script debugging
2. In VS 2008: Run the project first. Do not set breakpoint in your document first
3. In VS 2008: Check your solution explorer on the top. You will find [script document]. Double click to open html page and set breakpoint.

Tuesday, April 14, 2009

JQuery code for inline edit

<html>
<body>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>

<span class="editName">Test</span>
<input id="newName" name="editName" style="display: none" type="text" />

<script type="text/javascript">
$(function(){
$("span.editName").click(function(){
$(this).hide();
$(this).next("input#newName").show().focus();
});
});
</script>
</body>
</html>

$(document).ready()

Traditionally Javascript events were attached to a document using an “onload” attribute in the tag of the page.

The $(document).ready() function takes a function as its argument. (In this case, an anonymous function is created inline—a technique that is used throughout the jQuery documentation.)

Understanding Selectors: the Backbone of jQuery

$(document);
The first option will apply the jQuery library methods to a DOM object (in this case, the document object).
$(’#mydiv’)
The second option will select every <div> that has the <id> attribute set to “mydiv”.
$(’p.first’)
The third option will select all of the <p> tags with the class of “first”.
$(’p[title="Hello"]‘)
This option will select from the page all <p> tags that have a title of “Hello”. Techniques like this enable the use of much more semantically correct (X)HTML markup, while still facilitating the DOM scripting required to create complex interactions.
$(’p[title^="H"]‘)
This enables the selection of all of the <p> tags on the page that have a title that starts with the letter H.

Try simple JQuery/javascript online

http://www.w3schools.com/JS/tryit.asp?filename=tryjs_text
Jquey reference online
<html>
<body>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>

<script type="text/javascript">
document.write("Hello World!");
$(
function()
{
alert('hi');
}
)
</script>

</body>
</html>

Thursday, April 9, 2009

onload event in JQuery

<script type="text/javascript">
$(function() {
alert("This is equal to Form_Load in JQuery");
});
</script>

If getJSON in JQuery can not find exact signature method in Controller, it fails silently.... (ASP.NET MVC)

it fails silently....
Microsoft should put a couple of exclaimation marrk for this documentation somewherem, so we can see to save us sometime!!!!!!!!!!!!!!!!!!!!!!!!!

Example:
If you call getJSON in client side:
$.getJSON('/Home/GetList', { id: $("#country").val() },
You have to create an action in controller in following:
public JsonResult GetList(string id)
{
return Json(test.ToList());
}

But if you:
public JsonResult GetList(int id)
{
return Json(test.ToList());
}

You got nothing!!!!!!!!!!!!!!!!

Tuesday, April 7, 2009

Thursday, April 2, 2009

LINQ is pronounced link, "LIN Cue"

"link" is better to show what LINQ does.

Wednesday, April 1, 2009

How to create a text file on the fly, let user download it in ASP.NET

StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
sw.WriteLine("Name list");
Response.Clear();
Response.ContentType = "application/octet-stream";
Response.AppendHeader("content-disposition", "attachment;filename=teamlist.txt");
Response.Flush();
Response.Write(sb);
Response.End();

HTML encode link, helper to show code in blog

Link

Codes example for why use Lambda: how to find a distinct id list, and pass it into another method

Before Lambda:
List<Person> result = GetFromSomeWhere();

List<string> distinctids= new List<string>();
foreach (Person one in result)
{
if (!distinctids.Contains(one .Id.ToString()))
distinctids.Add(one .Id.ToString());
}

foreach (string id in distinctids)
{
DisplayPerson(id);
}

After:
List<Person> result = GetFromSomeWhere();
var result = result.Select(p=> p.Id).Distinct().ToList() ;
result.ForEach(id=>DisplayPerson(id));

Tuesday, March 31, 2009

The most important concepts, design pattern, in MVC ASP.NET

It is better to read something about those concepts, otherwise, it will confuse you for a while.

1. MVC design patthern
2. Controller, Action, ViewData, html helpers
3. JQuery
4 StructureMap, Dependency Injection and Inversion of Control

Wednesday, March 25, 2009

Monday, March 23, 2009

Codes example for why use Lambda

Consider this example:
 string person = people.Find(person => person.Contains("Joe"));

versus
 public string FindPerson(string nameContains, List<string> persons)
 
{
     
foreach (string person in persons)
         
if (person.Contains(nameContains))
             
return person;
     
return null;
 
}