Professional Documents
Culture Documents
If you use Microsoft® Visual C++® .NET, you can write managed code
using Visual C++, which provides the benefits of a managed execution
environment as well as access to powerful capabilities and expressive
data types that you are familiar with. Additional runtime features
include:
• Cross-language integration, especially cross-language
inheritance.
• The ability to compile once and run on any CPU and operating
system that supports the runtime.
You can also write managed code using the C# language, which
provides the following benefits:
• Complete object-oriented design.
• Garbage collection.
4. Running code.
Choosing a Compiler
To obtain the benefits provided by the common language runtime
(CLR), you must use one or more language compilers that target the
runtime, such as Visual Basic, C#, Visual C++, JScript, or one of many
third-party compilers such as an Eiffel, Perl, or COBOL compiler.
Because it is a multilanguage execution environment, the runtime
supports a wide variety of data types and language features. The
language compiler you use determines which runtime features are
available, and you design your code using those features. Your
compiler, not the runtime, establishes the syntax your code must use.
If your component must be completely usable by components written
in other languages, your component's exported types must expose
only language features that are included in the Common Language
Specification (CLS). You can use the CLSCompliantAttribute attribute
to ensure that your code is CLS-compliant. For details, see Writing
CLS-Compliant Code.
Compiling to MSIL
When compiling to managed code, the compiler translates your source
code into Microsoft intermediate language (MSIL), which is a CPU-
independent set of instructions that can be efficiently converted to
native code. MSIL includes instructions for loading, storing, initializing,
and calling methods on objects, as well as instructions for arithmetic
and logical operations, control flow, direct memory access, exception
handling, and other operations. Before code can be run, MSIL must be
converted to CPU-specific code, usually by a just-in-time (JIT)
compiler. Because the common language runtime supplies one or more
JIT compilers for each computer architecture it supports, the same set
of MSIL can be JIT-compiled and run on any supported architecture.
When a compiler produces MSIL, it also produces metadata. Metadata
describes the types in your code, including the definition of each type,
the signatures of each type's members, the members that your code
references, and other data that the runtime uses at execution time.
The MSIL and metadata are contained in a portable executable (PE)
file that is based on and extends the published Microsoft PE and
common object file format (COFF) used historically for executable
content. This file format, which accommodates MSIL or native code as
well as metadata, enables the operating system to recognize common
language runtime images. The presence of metadata in the file along
with the MSIL enables your code to describe itself, which means that
there is no need for type libraries or Interface Definition Language
(IDL). The runtime locates and extracts the metadata from the file as
needed during execution.
Code Verification
As part of compiling MSIL to native code, the MSIL code must pass a
verification process unless an administrator has established a security
policy that allows the code to bypass verification. Verification examines
MSIL and metadata to find out whether the code is type safe, which
means that it only accesses the memory locations it is authorized to
access. Type safety helps isolate objects from each other and
therefore helps protect them from inadvertent or malicious corruption.
It also provides assurance that security restrictions on code can be
reliably enforced.
The runtime relies on the fact that the following statements are true
for code that is verifiably type safe:
• A reference to a type is strictly compatible with the type being
referenced.
Running Code
The common language runtime provides the infrastructure that
enables managed execution to take place as well as a variety of
services that can be used during execution. Before a method can be
run, it must be compiled to processor-specific code. Each method for
which Microsoft intermediate language (MSIL) has been generated is
just-in-time-compiled (JIT-compiled) when it is called for the first
time, and then run. The next time the method is run, the existing JIT-
compiled native code is run. The process of JIT-compiling and then
executing the code is repeated until execution is complete.
During execution, managed code receives services such as garbage
collection, security, interoperability with unmanaged code, cross-
language debugging support, and enhanced deployment and
versioning support.
In Microsoft Windows XP and Windows Vista, the operating system
loader checks for managed modules by examining a bit in the common
object file format (COFF) header. The bit being set denotes a managed
module. If the loader detects managed modules, it loads mscoree.dll,
and _CorValidateImage and _CorImageUnloading notify the
loader when the managed module images are loaded and unloaded.
_CorValidateImage performs the following actions:
1. Ensures that the code is valid managed code.
• Reference types
Variables that are value types each have their own copy of the data,
and therefore operations on one variable do not affect other variables.
Variables that are reference types can refer to the same object;
therefore, operations on one variable can affect the same object
referred to by another variable.
All types derive from the System..::.Object base type.
The following example shows the difference between reference types
and value types.
using System;
class Class1
{
public int Value = 0;
}
class Test
{
static void Main() {
int val1 = 0;
int val2 = val1;
val2 = 123;
Class1 ref1 = new Class1();
Class1 ref2 = ref1;
ref2.Value = 123;
Console.WriteLine("Values: {0}, {1}", val1, val2);
Console.WriteLine("Refs: {0}, {1}", ref1.Value,
ref2.Value);
}
}
output
Values: 0, 123
Refs: 123, 123
The following diagram illustrates how these various types are related.
Note that instances of types can be simply value types or self-
describing types, even though there are subcategories of these types.
Type classification
For more information about each type, see value types, enumerations,
classes, delegates, arrays, interfaces, and pointers.
Values and Objects
Values are binary representations of data, and types provide a way of
interpreting this data. A value type is stored directly as a binary
representation of the type's data. The value of a reference type is the
location of the sequence of bits that represent the type's data.
Every value has an exact type that completely defines the value's
representation and the operations that are defined on the value.
Values of self-describing types are called objects. While it is always
possible to determine the exact type of an object by examining its
value, you cannot do so with a value type or pointer type. A value can
have more than one type. A value of a type that implements an
interface is also a value of that interface type. Likewise, a value of a
type that derives from a base type is also a value of that base type.
Types and Assemblies
The runtime uses assemblies to locate and load types. The assembly
manifest contains the information that the runtime uses to resolve all
type references made within the scope of the assembly.
A type name in the runtime has two logical parts: the assembly name
and the name of the type within the assembly. Two types with the
same name but in different assemblies are defined as two distinct
types.
Assemblies provide consistency between the scope of names seen by
the developer and the scope of names seen by the runtime system.
Developers author types in the context of an assembly. The content of
the assembly a developer is building establishes the scope of names
that will be available at run time.
Types and Namespaces
From the viewpoint of the runtime, a namespace is just a collection of
type names. Particular languages might have constructs and
corresponding syntax that help developers form logical groups of
types, but these constructs are not used by the runtime when binding
types. Thus, both the Object and String classes are part of the
System namespace, but the runtime only recognizes the full names of
each type, which are System..::.Object and System..::.String,
respectively.
You can build a single assembly that exposes types that look like they
come from two different hierarchical namespaces, such as
System.Collections and System.Windows.Forms. You can also build
two assemblies that both export types whose names contain
MyDll.MyClass.
• Perform I/O.
A 16-bit
Int16 signed Short short short short
integer.
int
A 32-bit
Int32 signed Integer int -or- int
integer.
long
A 64-bit
Int64 signed Long long __int64 long
integer.
UInt16 A 16-bit UShort ushort unsigned UInt16
unsigned short
integer.
Not CLS-
compliant.
A 32-bit unsigned
unsigned int
UInt32 integer. UInteger uint -or- UInt32
Not CLS- unsigned
compliant. long
A 64-bit
unsigned
unsigned
UInt64 integer. ULong ulong UInt64
__int64
Not CLS-
compliant.
A single-
precision
Floating (32-bit)
Single Single float float float
point floating-
point
number.
A double-
precision
(64-bit)
Double Double double double double
floating-
point
number.
A Boolean
Logical Boolean value (true Boolean bool bool bool
or false).
A Unicode
Other Char (16-bit) Char char wchar_t char
character.
A decimal
Decimal (128-bit) Decimal decimal Decimal Decimal
value.
IntPtr A signed IntPtr IntPtr IntPtr IntPtr
integer
No built-in No built- No built-in
whose size
type. in type. type.
depends on
the
underlying
platform (a
32-bit value
on a 32-bit
platform and
a 64-bit
value on a
64-bit
platform).
An unsigned
integer
whose size
depends on
the
underlying
platform (a
UIntPtr UIntPtr UIntPtr
32- bit value
UIntPtr on a 32-bit No built-in No built- No built-in UIntPtr
platform and type. in type. type.
a 64-bit
value on a
64-bit
platform).
Not CLS-
compliant.
The root of
Class
Object the object Object object Object* Object
objects
hierarchy.
An
immutable,
fixed-length
String String string String* String
string of
Unicode
characters.
In addition to the base data types, the System namespace contains
over 100 classes, ranging from classes that handle exceptions to
classes that deal with core runtime concepts, such as application
domains and the garbage collector. The System namespace also
contains many second-level namespaces.
For more information about namespaces, browse the .NET Framework
Class Library reference. The reference documentation provides a brief
overview of each namespace as well as a formal description of each
type and its members.
Delegate types are derived from the Delegate class in the .NET
Framework. Delegate types are sealed—they cannot be derived from—
and it is not possible to derive custom classes from Delegate. Because
the instantiated delegate is an object, it can be passed as a
parameter, or assigned to a property. This allows a method to accept a
delegate as a parameter, and call the delegate at some later time. This
is known as an asynchronous callback, and is a common method of
notifying a caller when a long process has completed. When a delegate
is used in this fashion, the code using the delegate does not need any
knowledge of the implementation of the method being used. The
functionality is similar to the encapsulation interfaces provide. For
more information, see When to Use Delegates Instead of Interfaces.
Another common use of callbacks is defining a custom comparison
method and passing that delegate to a sort method. It allows the
caller's code to become part of the sort algorithm. The following
example method uses the Del type as a parameter:
public void MethodWithCallback(int param1, int param2, Del
callback)
{
callback("The number is: " + (param1 +
param2).ToString());
}
You can then pass the delegate created above to that method:
MethodWithCallback(1, 2, handler);
• The class using the interface will want to cast that interface to
other interface or class types.
using System;
Console.WriteLine("Hello, World!");
Instead of:
C#
System.Console.WriteLine("Hello, World!");
The using Directive (C# Reference) can also be used to create an alias
for a namespace. For example, if you are using a previously written
namespace that contains nested namespaces, you might want to
declare an alias to provide a shorthand way of referencing one in
particular, as in the following example:
C#
namespace SampleNamespace
{
class SampleClass
{
public void SampleMethod()
{
System.Console.WriteLine(
"SampleMethod inside SampleNamespace");
}
}
class Program
{
static void Main(string[] args)
{
// Displays "SampleMethod inside
SampleNamespace."
SampleClass outer = new SampleClass();
outer.SampleMethod();
C#
• The class name C2 is used two times in this code. However, the
fully qualified names are unique. The first instance of C2 is
declared inside C1; therefore, its fully qualified name is:
N1.C1.C2. The second instance of C2 is declared inside a
namespace N2; therefore, its fully qualified name is N1.N2.C2.
Using the previous code segment, you can add a new class member,
C3, to the namespace N1.N2 as follows:
C#
// OK
Alias.WriteLine("Hi");
}
}
Remember that the word global is not a predefined alias; therefore,
global.X does not have any special meaning. It acquires a special
meaning only when it is used with ::.
A warning (see Compiler Warning (level 2) CS0440) is generated if you
define an alias named global because global:: always references the
global namespace and not an alias. For example, the following line
generates the warning:
C#
class MainClass
{
static int Main(string[] args)
{
// Test if input arguments were supplied:
if (args.Length == 0)
{
System.Console.WriteLine("Please enter a
numeric argument.");
System.Console.WriteLine("Usage: Factorial
<num>");
return 1;
}
// Print result.
if (result == -1)
System.Console.WriteLine("Input must be >= 0
and <= 20.");
else
System.Console.WriteLine("The Factorial of {0}
is {1}.", num, result);
return 0;
}
}
// If 3 is entered on command line, the
// output reads: The factorial of 3 is 6.
:fail
echo Execution Failed
echo return value = %ERRORLEVEL%
goto end
:good
echo Execution succeeded
echo Return value = %ERRORLEVEL%
goto end
:end
Sample Output
Execution succeeded
Return value = 0
The compiler uses type information to make sure that all operations
that are performed in your code are type safe. For example, if you
declare a variable of type int, the compiler allows you to use the
variable in addition and subtraction operations. If you try to perform
those same operations on a variable of type bool, the compiler
generates an error, as shown in the following example:
C#
Note:
You can see that the most commonly used types are all organized in
the System namespace. However, the namespace in which a type is
contained has no relation to whether it is a value type or reference
type.
Value Types
Value types derive from System..::.ValueType, which derives from
System..::.Object. Types that derive from System..::.ValueType have
special behavior in the CLR. Value type variables directly contain their
values, which means that the memory is allocated inline in whatever
context the variable is declared. There is no separate heap allocation
or garbage collection overhead for value-type variables.
There are two categories of value types: struct and enum.
The built-in numeric types are structs, and they have properties and
methods that you can access:
C#
C# Language Specification
For more information about types, see the following sections in the C#
Language Specification:
• 1.3 Types and variables
See Also
Concepts
C# Programming Guide
Conversion of XML Data Types
Reference
Data Types Compared in Different Languages
Integral Types Table (C# Reference)
Other Resources
C# Reference
Change History
Date History Reason
Fixed an error in the
February 2009 Customer feedback.
MaxValue example.
July 2008 Added introductory Information enhancement.
information and information
about type declarations, the
common type system, value
and reference types, literals,
and generic types.
Implicit Conversions
For built-in numeric types, an implicit conversion can be made when
the value to be stored can fit into the variable without being truncated
or rounded off. For example, a variable of type long (8 byte integer)
can store any value that an int (4 bytes on a 32-bit computer) can
store. In the following example, the compiler implicitly converts the
value on the right to a type long before assigning it to bigNum.
C#
class UnSafeCast
{
static void Main()
{
Test(new Mammal());
}
C# provides the is and as operators to enable you to test for
compatibility before actually performing a cast. For more information,
see How to: Safely Cast by Using as and is Operators (C#
Programming Guide).
C# Language Specification
For more information about casting and type conversions, see the
following sections in the C# Language Specification:
• 7.6.6 Cast Expressions
try
{
int j = (short)o; // attempt to unbox
System.Console.WriteLine("Unboxing OK.");
}
catch (System.InvalidCastException e)
{
System.Console.WriteLine("{0} Error: Incorrect
unboxing.", e.Message);
}
}
}
This program outputs:
Specified cast is not valid. Error: Incorrect unboxing.
If you change the statement:
• Copying the value from the instance into the value-type variable.
For the unboxing of value types to succeed at run time, the item being
unboxed must be a reference to an object that was previously created
by boxing an instance of that value type. Attempting to unbox null
causes a NullReferenceException. Attempting to unbox a reference to
an incompatible value type causes an InvalidCastException.
C# Language Specification
For more information, see the following sections in the C# Language
Specification:
• 4.3.1 Boxing Conversions
Related Sections
For more information:
• Reference Types
• Value Types
C# Language Specification
For more information, see the following section in the C# Language
Specification:
• 4.3 Boxing and Unboxing
See Also
Concepts
C# Programming Guide
Change History
Date History Reason
Added information about exceptions to
July 2009 Customer feedback.
"Unboxing" section.
Consolidated previously separate boxing
July 2008 Content bug fix.
and unboxing topics into this topic.
if (!parsed)
Console.WriteLine("Int32.TryParse could not parse '{0}'
to an int.\n", inputString);
// Output: Int32.TryParse could not parse 'abc' to an int
The MVC pattern helps you create applications that separate the
different aspects of the application (input logic, business logic, and UI
logic), while providing a loose coupling between these elements. The
pattern specifies where each kind of logic should be located in the
application. The UI logic belongs in the view. Input logic belongs in the
controller. Business logic belongs in the model. This separation helps
you manage complexity when you build an application, because it
enables you to focus on one aspect of the implementation at a time.
For example, you can focus on the view without depending on the
business logic.
The loose coupling between the three main components of an MVC
application also promotes parallel development. For example, one
developer can work on the view, a second developer can work on the
controller logic, and a third developer can focus on the business logic
in the model.
Support for Test-Driven Development
In addition to managing complexity, the MVC pattern makes it easier
to test applications than it is to test a Web Forms-based ASP.NET Web
application. For example, in a Web Forms-based ASP.NET Web
application, a single class is used both to display output and to
respond to user input. Writing automated tests for Web Forms-based
ASP.NET applications can be complex, because to test an individual
page, you must instantiate the page class, all its child controls, and
additional dependent classes in the application. Because so many
classes are instantiated to run the page, it can be hard to write tests
that focus exclusively on individual parts of the application. Tests for
Web Forms-based ASP.NET applications can therefore be more difficult
to implement than tests in an MVC application. Moreover, tests in a
Web Forms-based ASP.NET application require a Web server. The MVC
framework decouples the components and makes heavy use of
interfaces, which makes it possible to test individual components in
isolation from the rest of the framework.
When to Create an MVC Application
You must consider carefully whether to implement a Web application
by using either the ASP.NET MVC framework or the ASP.NET Web
Forms model. The MVC framework does not replace the Web Forms
model; you can use either framework for Web applications. (If you
have existing Web Forms-based applications, these continue to work
exactly as they always have.)
Before you decide to use the MVC framework or the Web Forms model
for a specific Web site, weigh the advantages of each approach.
Advantages of an MVC-Based Web Application
The ASP.NET MVC framework offers the following advantages:
• It makes it easier to manage complexity by dividing an
application into the model, the view, and the controller.
• It does not use view state or server-based forms. This makes the
MVC framework ideal for developers who want full control over
the behavior of an application.
End Sub
Sub Application_Start()
RegisterRoutes(RouteTable.Routes)
End Sub
End Class
C#
routes.MapRoute(
"Default",
// Route name
"{controller}/{action}/{id}",
// URL with parameters
new { controller = "Home", action = "Index", id
= "" } // Parameter defaults
);
The following table lists the stages of execution for an MVC Web
project.
Stage Details
Receive first
In the Global.asax file, Route objects are added to the
request for the
RouteTable object.
application
The UrlRoutingModule module uses the first matching
Perform Route object in the RouteTable collection to create the
routing RouteData object, which it then uses to create a
RequestContext object.
Create MVC The MvcRouteHandler object creates an instance of the
request MvcHandler class and passes the RequestContext
handler instance to the handler.
The MvcHandler object uses the RequestContext
Create instance to identify the IControllerFactory object
controller (typically an instance of the DefaultControllerFactory
class) to create the controller instance with.
Execute The MvcHandler instance calls the controller's Execute
controller method.
For controllers that inherit from the ControllerBase
class, the ControllerActionInvoker object that is
Invoke action associated with the controller determines which action
method of the controller class to call, and then calls that
method.
The action method receives user input, prepares the
appropriate response data, and then executes the result
by returning a result type. The built-in result types that
Execute result can be executed include the following: ViewResult
(which renders a view and is the most-often used result
type), RedirectToRouteResult, RedirectResult,
ContentResult, JsonResult, FileResult, and EmptyResult.
Walkthrough: Creating a Basic MVC Project with Unit Tests in Visual Studio
[Note: This topic is pre-release documentation and is subject to
change in future releases. Blank topics are included as placeholders.]
This walkthrough shows you how to create an ASP.NET MVC
application in Visual Studio. In this walkthrough, you will create and
run the sample MVC application. Then you will customize the
application by adding a controller and a view.
In addition, this walkthrough shows how to use test-driven
development (TDD). In the walkthrough, you create a project that
contains unit tests for the MVC application.
A Visual Studio project with source code is available to accompany this
topic: Download.
Prerequisites
In order to complete this walkthrough, you will need:
• Microsoft Visual Studio 2008 Service Pack 1 or later.
Note
Visual Studio Standard Edition and Visual Web Developer Express
do not do not support unit-test projects. You can use these
versions of Visual Studio to run the parts of this walkthrough that
pertain to creating and running an ASP.NET MVC project.
However, you will not be able to work with unit tests as described
in this walkthrough.
• ASP.NET MVC 2. You can download the framework from the
ASP.NET MVC 2 page on the Microsoft Download Center.
7. If you want the name of the solution to differ from the project
name, enter a name in the Solution Name box.
Note
If you are using the Standard or Express editions of Visual Studio,
the Create Unit Test Project dialog box is not displayed.
Instead, the new MVC application project is generated without a
test project.
10. Select Yes, create a unit test project.
• Views, which is for view page files. This folder contains three
subfolders: Account, Home, and Shared. The Account folder
contains views that are used as UI for logging in and changing
passwords. The Home folder contains an Index view (the default
starting page for the application) and an About page view. The
Shared folder contains the master-page view for the application.
4. Click Add.
Visual Basic
C#
4. Click Add.
Visual Basic
कोड कॉपी करें
Imports System
Imports System.Collections.Generic
Imports System.Text
Imports System.Web.Mvc
Imports Microsoft.VisualStudio.TestTools.UnitTesting
Imports MvcBasicWalkthrough
<TestClass()> _
Public Class MapsControllerTest
Private testContextInstance As TestContext
'''<summary>
'''Gets or sets the test context which provides
'''information about and functionality for the
current test run.
'''</summary>
Public Property TestContext() As TestContext
Get
Return testContextInstance
End Get
Set(ByVal value As TestContext)
testContextInstance = value
End Set
End Property
<TestMethod()> _
Public Sub ViewMaps()
' Arrange
Dim controller As MapsController = New
MapsController()
' Act
Dim result As ViewResult =
controller.ViewMaps()
' Assert
Assert.IsNotNull(result)
End Sub
End Class
C#
namespace MvcBasicWalkthrough.Tests.Controllers
{
[TestClass]
public class MapsControllerTest
{
[TestMethod]
public void ViewMaps()
{
// Arrange
MapsController controller = new
MapsController();
// Act
ViewResult result = controller.ViewMaps()
as ViewResult;
// Assert
Assert.IsNotNull(result);
}
}
}
This code defines the unit tests for the action method that you
will finish later.
Visual Basic
C#
कोड कॉपी करें
public ActionResult ViewMaps()
{
return View();
}
2. Save and close the file.
Adding a View
Next, you will add a Maps view. To keep the views organized, you will
first add a Maps folder under the Views folder.
3. Clear the Create a partial view (.ascx) check box and the
Create a strongly-typed view check box.
4. Select the Select master page check box and set the master
page to ~/Views/Shared/Site.Master.
6. Click Add.
None
function GetMap(mapID)
{
switch (mapID)
{
case 'Seattle':
map = new VEMap('earthMap');
map.LoadMap(new VELatLong(47.6,
-122.33), 10 ,'i', true);
break;
case 'LasVegas':
map = new VEMap('earthMap');
map.LoadMap(new VELatLong(36.17,
-115.14), 10 ,'i' ,true);
break;
case 'SaltLake':
map = new VEMap('earthMap');
map.LoadMap(new VELatLong(40.75,
-111.89), 10 ,'i' ,true);
break;
case 'Dallas':
map = new VEMap('earthMap');
map.LoadMap(new VELatLong(32.78,
-96.8), 10 ,'i' ,true);
break;
case 'Chicago':
map = new VEMap('earthMap');
map.LoadMap(new VELatLong(41.88,
-87.62), 10 ,'i' ,true);
break;
case 'NewYork':
map = new VEMap('earthMap');
map.LoadMap(new VELatLong(40.7, -74),
10 ,'i' ,true);
break;
case 'Rio':
map = new VEMap('earthMap');
map.LoadMap(new VELatLong(-22.91,
-43.18), 10 ,'i' ,true);
break;
case 'Paris':
map = new VEMap('earthMap');
map.LoadMap(new VELatLong(48.87,
2.33), 10 ,'i' ,true);
break;
case 'Naples':
map = new VEMap('earthMap');
map.LoadMap(new VELatLong(40.83,
14.25), 10 ,'i' ,true);
break;
case 'Keta':
map = new VEMap('earthMap');
map.LoadMap(new VELatLong(5.92,
0.983), 10 ,'i' ,true);
break;
case 'Beijing':
map = new VEMap('earthMap');
map.LoadMap(new VELatLong(39.91,
116.39), 10 ,'i' ,true);
break;
case 'Sydney':
map = new VEMap('earthMap');
map.LoadMap(new VELatLong(-33.86,
151.21), 10 ,'i' ,true);
}
}
</script>
This markup defines a drop-down list for selecting a map and the
JavaScript logic for retrieving the selected map from the
Microsoft Virtual Earth Web service.
1. In the Shared folder, open the Site.master file and locate the
unordered list (ul element) in the div element whose ID is
"menucontainer".
2. Add the following code to the list between the Index and About
Us tabs:
None
The results are displayed in the Test Results window. This time
the tests pass.
• For more information about MVC models, see Models and Model
Binders in MVC Applications.
• Handling all errors that might occur during the execution of the
action method.
Note
To help secure access to controllers and action methods, you can
use the PrincipalPermissionAttribute class.
All controller classes must be named by using the "Controller" suffix.
The following example shows the sample controller class, which is
named HomeController. This controller class contains action methods
that render view pages.
Visual Basic
Return View()
End Function
return View();
}
Return View()
End Function
Return View("FormResults")
End Function
End Class
C#
namespace MvcHtmlHelpers.Controllers
{
[HandleError]
public class HomeController : Controller
{
public ActionResult Index()
{
ViewData["Message"] = "Welcome to ASP.NET MVC!";
return View();
}
return View("FormResults");
}
}
}
The following example shows the Index view.
Visual Basic
<fieldset>
<legend>Fields</legend>
<p>
<label for="Id">Id:</label>
<%= Html.TextBox("Id", Model.Id) %>
<%= Html.ValidationMessage("Id", "*") %>
</p>
<p>
<label for="Name">Name:</label>
<%= Html.TextBox("Name", Model.Name) %>
<%= Html.ValidationMessage("Name", "*") %>
</p>
<p>
<label for="Age">Age:</label>
<%= Html.TextBox("Age", Model.Age) %>
<%= Html.ValidationMessage("Age", "*") %>
</p>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
<% End Using %>
<div>
<%=Html.ActionLink("Back to List", "Index") %>
</div>
C#
<fieldset>
<legend>Fields</legend>
<p>
<label for="Id">Id:</label>
<%= Html.TextBox("Id", Model.Id) %>
<%= Html.ValidationMessage("Id", "*") %>
</p>
<p>
<label for="Name">Name:</label>
<%= Html.TextBox("Name", Model.Name) %>
<%= Html.ValidationMessage("Name", "*") %>
</p>
<p>
<label for="Age">Age:</label>
<%= Html.TextBox("Age", Model.Age) %>
<%= Html.ValidationMessage("Age", "*") %>
</p>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
<% } %>
<div>
<%=Html.ActionLink("Back to List", "Index") %>
</div>
The following example shows the action method that receives a Person
object from the Edit view, checks its validity against the model,
updates a list of Person objects, and then redirects to the Index
action.
Visual Basic
Return RedirectToAction("Index")
End Function
C#
return RedirectToAction("Index");
}
Passing State Between Action Methods
Action methods might have to pass data to the next action, such as if
an error occurs when a form is being posted. In that case, the user
might be redirected to another view that displays error information.
An action method can store data in the controller's
TempDataDictionary object before it calls the controller's
RedirectToAction method to invoke the next action. The TempData
property value is stored in session state. The next action method can
get values from the TempDataDictionary object to process or to
display in its own view. The value of TempData persists only from one
request to the next.
The following example shows a data class that is used to trap an error
and to transfer data between actions.
Visual Basic
' CustomersController
' No errors
' ...
Return View()
End Function
' ...
Return View()
End Function
C#
// CustomersController
First name:
<input type="text" name="firstName" value="<%=
ViewData["FirstName"] %>" />
<br />
Last name:
<input type="text" name="lastName" value="<%=
ViewData["LastName"] %>" />
<br />
<input type="submit" value="Insert" />
</form
• System.Web.Mvc
• System.Web.Routing
• System.Web.Abstractions
All the files that are required in order to deploy the application
are copied to the target folder.
Silverlight
.NET Framework Class Library for Silverlight
The .NET Framework class library consists of classes, interfaces, and
value types that are included with the .NET Framework for Silverlight.
The class library provides a reusable set of classes, components,
controls, and user interface elements that can be incorporated into
Silverlight-based applications.
In This Section
The .NET Framework for Silverlight class library provides the following
namespaces, which are documented in detail in this reference.
Microsoft.Internal
Supports the .NET Framework for Silverlight infrastructure. This
namespace is not intended to be used directly from your code.
Microsoft.VisualBasic
Contains classes that support the Visual Basic runtime in Visual
Basic.
Microsoft.VisualBasic.CompilerServices
Contains internal-use only types that support the Visual Basic
compiler.
Microsoft.Win32.SafeHandles
Contains classes that are abstract derivations of safe handle
classes that provide common functionality supporting file and
operating system handles.
System
Contains fundamental classes and base classes that define
commonly used value and reference data types, events and
event handlers, interfaces, attributes, and processing
exceptions. Other classes provide services that support data type
conversion, method parameter manipulation, mathematics,
remote and local program invocation, application environment
management, and supervision of managed and unmanaged
applications.
System.CodeDom.Compiler
Contains a class that identifies code that is generated by a tool.
System.Collections
Contains the BitArray class, interfaces that are implemented by
various collection objects, and interfaces and a structure that let
you extract, enumerate, and compare objects in collections.
System.Collections.Generic
Contains interfaces and classes that define generic collections.
System.Collections.ObjectModel
Contains classes that can be used as collections in the object
model of a reusable library. Use these classes when properties or
methods return collections.
System.Collections.Specialized
Contains specialized and strongly typed collections.
System.ComponentModel
Provides classes that are used to implement the run-time and
design-time behavior of components and controls.
System.ComponentModel.DataAnnotations
Provides attribute classes that are used to define metadata for
entity classes.
System.Configuration.Assemblies
Contains classes that are used to configure an assembly.
System.Data.Services.Client
Represents the classes and members that applications can use to
interact with ADO.NET Data Services.
System.Data.Services.Common
Contains a class that indicates the key property or properties of
an entity.
System.Diagnostics
Provides classes that enable you to debug your applications and
to trace the execution of your code.
System.Diagnostics.CodeAnalysis
Contains classes for interaction with tools that analyze code for
conformance to coding conventions such as naming or security
rules.
System.Diagnostics.SymbolStore
Provides an interface that gives you access to debug symbol
information, such as source-line-to-MSIL (Microsoft intermediate
language) maps. Compilers that target the .NET Framework for
Silverlight can store the debug symbol information into
programmer's database (PDB) files. Debuggers and code profiler
tools can read the debug symbol information at run time.
System.Globalization
Contains classes that define culture-related information,
including the language, the country/region, the calendars in use,
the format patterns for dates, currency, and numbers, and the
sort order for strings. These classes are useful for writing
globalized (internationalized) applications.
System.IO
Contains types that enable reading and writing to data streams.
System.IO.IsolatedStorage
Contains types for creating and using a virtual file system.
Isolated storage provides safe client-side storage for partial trust
applications. In Silverlight, all I/O operations are restricted to
isolated storage and do not use the file system of the operating
system.
System.Json
Provides standards-based support for the serialization of
JavaScript Object Notation (JSON).
System.Linq
Contains classes and interfaces that support queries that use
Language-Integrated Query (LINQ).
System.Linq.Expressions
Contains types that enable language-level code expressions to
be represented as objects in the form of expression trees.
System.Net
Provides a simple programming interface for many of the
protocols used on networks today. The WebRequest and
WebResponse classes form the basis of pluggable protocols,
which enable you to develop applications that use Internet
resources without worrying about the specific details of the
individual protocols.
System.Net.Browser
Contains a class that represents the source of a Web request.
System.Net.NetworkInformation
Provides access to information on network availability and
notification of address changes for the local computer.
System.Net.Sockets
Provides a managed implementation of the sockets networking
interface for developers who need to tightly control access to the
network. On Windows, this namespace provides a managed
implementation of the Windows Sockets (Winsock) interface. On
Apple Macintosh OS X, this namespace provides a managed
implementation of the sockets interface based on Berkeley
Software Distribution (BSD) UNIX.
System.Reflection
Contains types that retrieve information about assemblies,
modules, members, parameters, and other entities in managed
code by examining their metadata. These types also can be used
to manipulate instances of loaded types, for example, to hook up
events or to invoke methods.
System.Reflection.Emit
Contains classes that enable a compiler or tool to emit metadata
and Microsoft intermediate language (MSIL) and optionally to
generate a PE file on disk. The primary clients of these classes
are script engines and compilers.
System.Resources
Provides classes and interfaces that enable developers to create,
store, and manage various culture-specific resources used in an
application.
System.Runtime.CompilerServices
Provides functionality for compiler writers who use managed
code to specify attributes in metadata that affect the run-time
behavior of the common language runtime.
System.Runtime.ConstrainedExecution
Defines a type that ensures that finalization code is marked as
critical. The type is intended for use in constrained execution
regions (CERs).
System.Runtime.InteropServices
Provides a wide variety of members that support COM interop
and platform invoke services.
System.Runtime.Serialization
Contains classes that can be used for serializing and deserializing
objects. Serialization is the process of converting an object or a
graph of objects into a linear sequence of bytes for either
storage or transmission to another location. Deserialization is the
process of taking in stored information and recreating objects
from it.
System.Runtime.Serialization.Json
Contains types for serializing objects to JavaScript Object
Notation (JSON) and deserializing objects from JSON.
System.Runtime.Versioning
Contains advanced types that support versioning in side-by-side
implementations of the .NET Framework for Silverlight.
System.Security
Provides the underlying structure of the .NET Framework for
Silverlight security system.
System.Security.Cryptography
Provides cryptographic services, including secure encoding and
decoding of data, as well as many other operations, such as
hashing, random number generation, and message
authentication.
System.Security.Cryptography.X509Certificates
Contains the common language runtime implementation of the
Authenticode X.509 v.3 certificate. This certificate is signed with
a private key that uniquely and positively identifies the holder of
the certificate.
System.Security.Permissions
Defines classes that control access to operations and resources
based on policy. This namespace supports the .NET Framework
for Silverlight infrastructure; none of its types are accessible to
application code.
System.Security.Principal
Defines a principal object that represents the security context
under which code is running.
System.ServiceModel
Contains the types necessary to build Silverlight-based client
applications that can be used to access distributed applications.
System.ServiceModel.Channels
Contains the types required to construct and modify the
messages used by clients to communicate with services, the
types of channels used to exchange messages, the channel
factories used to construct those channels, and the binding
elements used to configure them.
System.ServiceModel.Description
Contains the types required to construct and modify descriptions
of services, contracts, and endpoints that are used to build
service runtimes and to export metadata.
System.ServiceModel.Dispatcher
Contains the types necessary to modify the run-time execution
behavior of client applications.
System.ServiceModel.Security
Contains types related to security.
System.ServiceModel.Syndication
Contains the types that make up the Silverlight syndication
object model.
System.Text
Contains classes that represent Unicode and UTF-8 character
encodings; abstract base classes for converting blocks of
characters to and from blocks of bytes; and a helper class that
manipulates and formats String objects without creating
intermediate instances of String.
System.Text.RegularExpressions
Contains classes that provide access to the .NET Framework
regular expression engine. The namespace provides regular
expression functionality that can be used from any platform or
language that runs within the .NET Framework.
System.Threading
Provides classes and interfaces that enable multithreaded
programming.
System.Windows
Provides general presentation classes for Silverlight applications,
as well as the Silverlight base classes. These presentation
classes are often similar to classes that exist in the Windows
Presentation Foundation (WPF).
System.Windows.Automation
Contains classes that provide support for Silverlight UI
Automation clients.
System.Windows.Automation.Peers
Defines the AutomationPeer base class and a set of types that
derive from it and that correspond to Silverlight controls. Each
AutomationPeer exposes the corresponding Silverlight control to
UI Automation.
System.Windows.Automation.Provider
Contains interfaces for creating UI Automation providers.
System.Windows.Browser
Contains classes that enable the interaction between managed
code and JavaScript in Silverlight-based applications. This
functionality is referred to as the HTML Bridge feature.
System.Windows.Controls
Contains classes to create controls that enable a user to interact
with an application.
System.Windows.Controls.Primitives
Contains base classes and controls that are intended to be used
as part of other, more complex controls.
System.Windows.Data
Contains classes used for binding properties to data sources.
System.Windows.Documents
Contains classes that support basic document concepts in
Silverlight.
System.Windows.Ink
Provides classes to interact with and manipulate ink in
Silverlight.
System.Windows.Input
Contains classes that support input in a Silverlight-based
application.
System.Windows.Interop
Contains classes that provide managed code exposure for
properties of the Silverlight plug-in, which otherwise exist in the
HTML DOM of the hosting browser.
System.Windows.Markup
Contains classes that support Extensible Application Markup
Language (XAML) processing in Silverlight.
System.Windows.Media
Contains classes that enable integration of rich media, including
drawings, text, and audio/video content, in Silverlight-based
applications.
System.Windows.Media.Animation
Contains classes that support property animation functionality,
including timelines, storyboards, and key frames.
System.Windows.Media.Effects
Provides types that can be used to apply visual effects to bitmap
images.
System.Windows.Media.Imaging
Contains classes used to encode and decode bitmap images.
System.Windows.Messaging
Provides types that support messaging.
System.Windows.Navigation
Provides types that support navigation.
System.Windows.Resources
Contains a class that provides resource stream information for
application resources or other packages obtained through
Application..::.GetResourceStream.
System.Windows.Shapes
Contains a library of basic shapes that can be used in Extensible
Application Markup Language (XAML) or code. Also includes the
Path class, which can load path data to describe a compound
geometry either through an object model or an inline format.
System.Windows.Threading
Contains classes that support the Silverlight threading system.
System.Xml
Provides standards-based support for processing XML.
System.Xml.Linq
Contains the types for LINQ to XML, which is an in-memory XML
programming interface that enables you to modify XML
documents efficiently and easily.
System.Xml.Resolvers
Contains classes that provide support for prepopulating the
cache with DTDs or XML streams.
System.Xml.Schema
Contains the XML classes that provide standards-based support
for XML Schema definition language (XSD) schemas.
System.Xml.Serialization
Contains classes that are used to serialize objects into XML
format documents or streams.