All About ASP.NET and ASP.NET Core 2 Hosting BLOG

Tutorial and Articles about ASP.NET and the latest ASP.NET Core

ASP.NET 5 Hosting - ASPHostPortal.com :: Debugging jQuery in ASP.NET

clock February 10, 2015 07:17 by author Mark

When an ASP.NET developer uses jQuery or JavaScript (clientside programming) in his code, the question always arises of how to debug this code. We can debug in code behind with breakpoints. But what for clientside scripting. Some people say use "alert()", but I don't think this is a sufficient way to do it.
So the good news is that we have the "debugger" keyword to debug your line of code.
Use debugger before your code, where you want to start debugging.
See the following code:

<html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
        <script src="Scripts/jquery-1.7.1.min.js"></script>
        <script>
            $(document).ready(function () {
                $(':radio').click(function () {
                    debugger;
    //Get the value of Radio button
                    var _GetVal = $(this).attr('value');
                });
             });
        </script>
    </head>
    <body>
        <form id="form1" runat="server">
        <div>
           First
            <input type="radio" name="rd1" value="10" />
            <input type="radio" name="rd1" value="11" />
            Second
            <input type="radio" name="rd1" value="12" />
            <input type="radio" name="rd1" value="13" />
        </div>
        </form>
    </body>
    </html>

This is a simple ASP.NET in page code. When the user clicks a radio button, debugging will automatically start, due to the debugger command. In the above program, when the user clicks on the radio button we stored its value in the _Getval variable.

$(document).ready(function () {
                $(':radio').click(function () {
                    debugger;
    //Get the value of Radio button
                    var _GetVal = $(this).attr('value');
                });
             });

You can see that when I declare a _GetVal variable, before I use "debugger" because from here I want to start debugging. See the following images.
Figure 1: When user clicks in the radio

Figure 2: When the user presses F10 (the same way as what we did in code behind using a breakpoint).

In the image above you can see that the _GetVal value is 10 now. So with the use of the debugger you can start your debugging in ASP.NET.
And please remember, when you finish debugging or publish your page, please remove debugger from your code.
If you have any query, Please send your valuable Comments. Happy Programming

TOP No#1 Recommended ASP.NET Hosting

ASPHostPortal.com

ASPHostPortal.com  is the leading provider of Windows hosting and affordable ASP.NET Hosting. ASPHostPortal proudly working to help grow the backbone of the Internet, the millions of individuals, families, micro-businesses, small business, and fledgling online businesses. ASPHostPortal has ability to support the latest Microsoft and ASP.NET technology, such as: WebMatrix, WebDeploy, Visual Studio 2015, .NET 5/ASP.NET 4.5.2, ASP.NET MVC 6.0/5.2, Silverlight 6 and Visual Studio Lightswitch, ASPHostPortal guarantees the highest quality product, top security, and unshakeable reliability, carefully chose high-quality servers, networking, and infrastructure equipment to ensure the utmost reliability.



ASPHostPortal.com Proudly Announces ASP.NET MVC 5 Hosting

clock July 12, 2013 08:44 by author Mike

ASPHostPortal.com is a premiere web hosting company that specializes in Windows and ASP.NET-based hosting, proudly announces the new Microsoft product, ASP.NET MVC 5 hosting to all new and existing customers.

ASP.NET MVC 5 is the latest update to Microsoft's popular MVC (Model-View-Controller) technology - an established web application framework. MVC enables developers to build dynamic, data-driven web sites. ASP.NET MVC 5 adds sophisticated features like single page applications, mobile optimization, adaptive rendering, and more. Here are some new features of ASP.NET MVC 5:

- ASP.NET Identity
- Bootstrap in the MVC template
- Authentication Filters
- Filter overrides

“We pride ourselves on offering the most up to date Microsoft services. We're pleased to launch this product today on our hosting environment” said Dean Thomas, Manager at ASPHostPortal.com. “We have always had a great appreciation for the products that Microsoft offers. With the launched of ASP.NET MVC 5 hosting services, we hope that developers and our existing clients can try this new features.”

ASPHostPortal.com is one of the Microsoft recommended hosting partner that provide most stable and reliable web hosting platform. With the new launch of ASP.NET MVC 5 into its feature, it will continue to keep ASPHostPortal as one of the front runners in the web hosting market. For more information about new ASP.NET MVC 5, please visit http://www.asphostportal.com.

About ASPHostPortal.com:
ASPHostPortal.com is a hosting company that best support in Windows and ASP.NET-based hosting. Services include shared hosting, reseller hosting, and sharepoint hosting, with specialty in ASP.NET, SQL Server, and architecting highly scalable solutions. As a leading small to mid-sized business web hosting provider, ASPHostPortal strive to offer the most technologically advanced hosting solutions available to all customers across the world. Security, reliability, and performance are at the core of hosting operations to ensure each site and/or application hosted is highly secured and performs at optimum level.



ASP.NET 4.5 Hosting - ASPHostPortal.com :: Tips to Prevent Cross-Site Scripting in ASP.NET

clock June 14, 2013 08:27 by author Ben

Summary
This How to shows how you can help protect your ASP.NET applications from cross-site scripting attacks by using proper input validation techniques and by encoding the output. It also describes a number of other protection mechanisms that you can use in addition to these two main countermeasures.

Cross-site scripting (XSS) attacks exploit vulnerabilities in Web page validation by injecting client-side script code. Common vulnerabilities that make your Web applications susceptible to cross-site scripting attacks include failing to properly validate input, failing to encode output, and trusting the data retrieved from a shared database. To protect your application against cross-site scripting attacks, assume that all input is malicious. Constrain and validate all input. Encode all output that could, potentially, include HTML characters. This includes data read from files and databases.

Contents

  • Objectives
  • Overview
  • Summary of Steps
  • Step 1. Check That ASP.NET Request Validation Is Enabled
  • Step 2. Review ASP.NET Code That Generates HTML Output
  • Step 3. Determine Whether HTML Output Includes Input Parameters
  • Step 4. Review Potentially Dangerous HTML Tags and Attributes
  • Step 5. Evaluate Countermeasures
  • Additional Considerations
  • Additional Resources

Objectives

  • Understand the common cross-site scripting vulnerabilities in Web page validation.
  • Apply countermeasures for cross-site scripting attacks.
  • Constrain input by using regular expressions, type checks, and ASP.NET validator controls.
  • Constrain output to ensure the browser does not execute HTML tags that contain script code.
  • Review potentially dangerous HTML tags and attributes and evaluate countermeasures.

Overview
Cross-site scripting attacks exploit vulnerabilities in Web page validation by injecting client-side script code. The script code embeds itself in response data, which is sent back to an unsuspecting user. The user's browser then runs the script code. Because the browser downloads the script code from a trusted site, the browser has no way of recognizing that the code is not legitimate, and Microsoft Internet Explorer security zones provide no defense. Cross-site scripting attacks also work over HTTP and HTTPS (SSL) connections.

One of the most serious examples of a cross-site scripting attack occurs when an attacker writes script to retrieve the authentication cookie that provides access to a trusted site and then posts the cookie to a Web address known to the attacker. This enables the attacker to spoof the legitimate user's identity and gain illicit access to the Web site.

Common vulnerabilities that make your Web application susceptible to cross-site scripting attacks include:

  • Failing to constrain and validate input.
  • Failing to encode output.
  • Trusting data retrieved from a shared database.

Guidelines
The two most important countermeasures to prevent cross-site scripting attacks are to:

  • Constrain input.
  • Encode output.

Constrain Input
Start by assuming that all input is malicious. Validate input type, length, format, and range.

  • To constrain input supplied through server controls, use ASP.NET validator controls such as RegularExpressionValidator and RangeValidator.
  • To constrain input supplied through client-side HTML input controls or input from other sources such as query strings or cookies, use the System.Text.RegularExpressions.Regex class in your server-side code to check for expected using regular expressions.
  • To validate types such as integers, doubles, dates, and currency amounts, convert the input data to the equivalent .NET Framework data type and handle any resulting conversion errors.

Encode Output
Use the AntiXSS.HtmlEncode method to encode output if it contains input from the user or from other sources such as databases. HtmlEncode replaces characters that have special meaning in HTML-to-HTML variables that represent those characters. For example, < is replaced with &lt; and " is replaced with &quot;. Encoded data does not cause the browser to execute code. Instead, the data is rendered as harmless HTML.

Similarly, use AntiXSS.UrlEncode to encode output URLs if they are constructed from input.

Summary of Steps
To prevent cross-site scripting, perform the following steps:

  • Step 1. Check that ASP.NET request validation is enabled.
  • Step 2. Review ASP.NET code that generates HTML output.
  • Step 3. Determine whether HTML output includes input parameters.
  • Step 4. Review potentially dangerous HTML tags and attributes.
  • Step 5. Evaluate countermeasures.

Step 1. Check That ASP.NET Request Validation Is Enabled
By default, request validation is enabled in Machine.config. Verify that request validation is currently enabled in your server's Machine.config file and that your application does not override this setting in its Web.config file. Check that validateRequest is set to true as shown in the following code example.

<system.web>
  <pages buffer="true" validateRequest="true" />
</system.web>

You can disable request validation on a page-by-page basis. Check that your pages do not disable this feature unless necessary. For example, you may need to disable this feature for a page if it contains a free-format, rich-text entry field designed to accept a range of HTML characters as input.

To test that ASP.NET request validation is enabled
1.
Create an ASP.NET page that disables request validation. To do this, set ValidateRequest="false", as shown in the following code example.

<%@ Page Language="C#" ValidateRequest="false" %>
<html>
 <script runat="server">
  void btnSubmit_Click(Object sender, EventArgs e)
  {
    // If ValidateRequest is false, then 'hello' is displayed
    // If ValidateRequest is true, then ASP.NET returns an exception
    Response.Write(txtString.Text);
  }
 </script>
 <body>
  <form id="form1" runat="server">
    <asp:TextBox id="txtString" runat="server"
                 Text="<script>alert('hello');</script>" />
    <asp:Button id="btnSubmit" runat="server"  
                OnClick="btnSubmit_Click"
                Text="Submit" />
  </form>
 </body>
</html>

2. Run the page. It displays Hello in a message box because the script in txtString is passed through and rendered as client-side script in your browser.

3. Set ValidateRequest="true" or remove the ValidateRequest page attribute and browse to the page again. Verify that the following error message is displayed.

A potentially dangerous Request.Form value was detected from the client (txtString="<script>alert('hello...").

This indicates that ASP.NET request validation is active and has rejected the input because it includes potentially dangerous HTML characters.

Note: Do not rely on ASP.NET request validation. Treat it as an extra precautionary measure in addition to your own input validation.

Step 2. Review ASP.NET Code That Generates HTML Output
ASP.NET writes HTML as output in two ways, using "Response.Write" and "<% = ". Search your pages to locate where HTML and URL output is returned to the client.

Step 3. Determine Whether HTML Output Includes Input Parameters
Analyze your design and your page code to determine whether the output includes any input parameters. These parameters can come from a variety of sources. The following list includes common input sources:

·         Form fields, such as the following.

Response.Write(name.Text);
Response.Write(Request.Form["name"]);
Query Strings
Response.Write(Request.QueryString["name"]);

·         Query strings, such as the following:

Response.Write(Request.QueryString["username"]);

·         Databases and data access methods, such as the following:

SqlDataReader reader = cmd.ExecuteReader();
Response.Write(reader.GetString(1));

Be particularly careful with data read from a database if it is shared by other applications.

·         Cookie collection, such as the following:

Response.Write(
Request.Cookies["name"].Values["name"]);

·         Session and application variables, such as the following:

Response.Write(Session["name"]);
Response.Write(Application["name"]);

In addition to source code analysis, you can also perform a simple test by typing text such as "XYZ" in form fields and testing the output. If the browser displays "XYZ" or if you see "XYZ" when you view the source of the HTML, your Web application is vulnerable to cross-site scripting.

To see something more dynamic, inject <script>alert('hello');</script> through an input field. This technique might not work in all cases because it depends on how the input is used to generate the output.

Step 4. Review Potentially Dangerous HTML Tags and Attributes
If you dynamically create HTML tags and construct tag attributes with potentially unsafe input, make sure you HTML-encode the tag attributes before writing them out.

The following .aspx page shows how you can write HTML directly to the return page by using the <asp:Literal> control. The code takes user input of a color name, inserts it into the HTML sent back, and displays text in the color entered. The page uses HtmlEncode to ensure the inserted text is safe.

<%@ Page Language="C#" AutoEventWireup="true"%>
<html>
  <form id="form1" runat="server">
    <div>
      Color:&nbsp;<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox><br />
      <asp:Button ID="Button1" runat="server" Text="Show color"
         OnClick="Button1_Click" /><br />
      <asp:Literal ID="Literal1" runat="server"></asp:Literal>
    </div>
  </form>
</html>

<script runat="server">
  private void Page_Load(Object Src, EventArgs e)
  {
    protected void Button1_Click(object sender, EventArgs e)
    {
      Literal1.Text = @"<span style=""color:"
        + Server.HtmlEncode(TextBox1.Text)
        + @""">Color example</span>";
    }          
  }
</Script>

Potentially Dangerous HTML Tags
While not an exhaustive list, the following commonly used HTML tags could allow a malicious user to inject script code:

  • <applet>
  • <body>
  • <embed>
  • <frame>
  • <script>
  • <frameset>
  • <html>
  • <iframe>
  • <img>
  • <style>
  • layer>
  • <link>
  • <ilayer>
  • <meta>
  • <object>

An attacker can use HTML attributes such as src, lowsrc, style, and href in conjunction with the preceding tags to inject cross-site scripting. For example, the src attribute of the <img> tag can be a source of injection, as shown in the following examples.

<img src="javascript:alert('hello');">
<img src="java&#010;script:alert('hello');">
<img src="java&#X0A;script:alert('hello');">

An attacker can also use the <style> tag to inject a script by changing the MIME type as shown in the following.

<style TYPE="text/javascript">
  alert('hello');
</style>

Step 5. Evaluate Countermeasures
When you find ASP.NET code that generates HTML using some input, you need to evaluate appropriate countermeasures for your specific application. Countermeasures include:

  • Encode HTML output.
  • Encode URL output.
  • Filter user input.

Encode HTML Output
If you write text output to a Web page and you do not know if the text contains HTML special characters (such as <, >, and &), pre-process the text by using the AntiXSS.HtmlEncode method as shown in the following code example. Do this if the text came from user input, a database, or a local file.

Response.Write(AntiXSS.HtmlEncode(Request.Form["name"]));

Do not substitute encoding output for checking that input is well-formed and correct. Use it as an additional security precaution.

Encode URL Output
If you return URL strings that contain input to the client, use the AntiXSS.UrlEncode method to encode these URL strings as shown in the following code example.

Response.Write(AntiXSS.UrlEncode(urlString));

Filter User Input
If you have pages that need to accept a range of HTML elements, for example through some kind of rich text input field, you must disable ASP.NET request validation for the page. If you have several pages that do this, create a filter that allows only the HTML elements that you want to accept. A common practice is to restrict formatting to safe HTML elements such as bold (<b>) and italic (<i>).

To safely allow restricted HTML input
1.
Disable ASP.NET request validation by the adding the ValidateRequest="false" attribute to the @Page directive.

2. Encode the string input with the HtmlEncode method.

3. Use a StringBuilder and call its Replace method to selectively remove the encoding on the HTML elements that you want to permit.

The following .aspx page code shows this approach. The page disables ASP.NET request validation by setting ValidateRequest="false". It HTML-encodes the input and then selectively allows the <b> and <i> HTML elements to support simple text formatting.

<%@ Page Language="C#" ValidateRequest="false"%>
<script runat="server">
  void submitBtn_Click(object sender, EventArgs e)
  {
    // Encode the string input
    StringBuilder sb = new StringBuilder(
                         AntiXSS.HtmlEncode(htmlInputTxt.Text));

  // Selectively allow  <b> and <i>
    sb.Replace("&lt;b&gt;", "<b>");
    sb.Replace("&lt;/b&gt;", "");
    sb.Replace("&lt;i&gt;", "<i>");
    sb.Replace("&lt;/i&gt;", "");
    Response.Write(sb.ToString());
  }
</script>


<html>
  <body>
    <form id="form1" runat="server">
      <div>
        <asp:TextBox ID="htmlInputTxt" Runat="server"
                     TextMode="MultiLine" Width="318px"
                     Height="168px"></asp:TextBox>
        <asp:Button ID="submitBtn" Runat="server"
                     Text="Submit" OnClick="submitBtn_Click" />
      </div>
    </form>
  </body>
</html>

Additional Considerations
In addition to the techniques discussed previously in this How to, use the following countermeasures as further safe guards to prevent cross-site scripting:

  • Set the correct character encoding.
  • Do not rely on input sanitization.
  • Use the HttpOnly cookie option.
  • Use the <frame> security attribute.
  • Use the innerText property instead of innerHTML.

Set the Correct Character Encoding
To successfully restrict valid data for your Web pages, you should limit the ways in which the input data can be represented. This prevents malicious users from using canonicalization and multi-byte escape sequences to trick your input validation routines. A multi-byte escape sequence attack is a subtle manipulation that uses the fact that character encodings, such as uniform translation format-8 (UTF-8), use multi-byte sequences to represent non-ASCII characters. Some byte sequences are not legitimate UTF-8, but they may be accepted by some UTF-8 decoders, thus providing an exploitable security hole.

ASP.NET allows you to specify the character set at the page level or at the application level by using the <globalization> element in the Web.config file. The following code examples show both approaches and use the ISO-8859-1 character encoding, which is the default in early versions of HTML and HTTP.

To set the character encoding at the page level, use the <meta> element or the ResponseEncoding page-level attribute as follows:

<meta http-equiv="Content Type"
      content="text/html; charset=ISO-8859-1" />
OR
<% @ Page ResponseEncoding="iso-8859-1" %>

To set the character encoding in the Web.config file, use the following configuration.

<configuration>
   <system.web>
      <globalization
         requestEncoding="iso-8859-1"
         responseEncoding="iso-8859-1"/>
   </system.web>
</configuration>

Validating Unicode Characters
Use the following code to validate Unicode characters in a page. using System.Text.RegularExpressions;
public class WebForm1 : System.Web.UI.Page
{
  private void Page_Load(object sender, System.EventArgs e)
  {
    // Name must contain between 1 and 40 alphanumeric characters
    // and (optionally) special characters such as apostrophes 
    // for names such as O'Dell
    if (!Regex.IsMatch(Request.Form["name"],
               @"^[\p{L}\p{Zs}\p{Lu}\p{Ll}\']{1,40}$"))
      throw new ArgumentException("Invalid name parameter");

    // Use individual regular expressions to validate other parameters
    ...
  }
}

The following explains the regular expression shown in the preceding code:

  • ^ means start looking at this position.
  • \p{ ..} matches any character in the named character class specified by {..}.
  • {L} performs a left-to-right match.
  • {Lu} performs a match of uppercase.
  • {Ll} performs a match of lowercase.
  • {Zs} matches separator and space.
  • 'matches apostrophe.
  • {1,40} specifies the number of characters: no less than 1 and no more than 40.
  • $ means stop looking at this position.

Do Not Rely on Input Sanitization
A common practice is for code to attempt to sanitize input by filtering out known unsafe characters. Do not rely on this approach because malicious users can usually find an alternative means of bypassing your validation. Instead, your code should check for known secure, safe input

Use the HttpOnly Cookie Option
The HttpOnly cookie attribute prevents client-side scripts from accessing a cookie from the document.cookie property. Instead, the script returns an empty string. The cookie is still sent to the server whenever the user browses to a Web site in the current domain.

Use the <frame> Security Attribute
You can set the security attribute for the <frame> and <iframe> elements. You can use the security attribute to apply the user's Restricted Sites Internet Explorer security zone settings to an individual frame or iframe. By default, the Restricted Sites zone does not support script execution.

If you use the security attribute, it must be set to "restricted" as shown in the following.

<frame security="restricted" src="http://www.somesite.com/somepage.htm"></frame>

Use the innerText Property Instead of innerHTML    
If you use the innerHTML property to build a page and the HTML is based on potentially untrusted input, you must use HtmlEncode to make it safe. To avoid having to remember to do this, use innerText instead. The innerText property renders content safe and ensures that scripts are not executed.

The following example shows this approach for two HTML <span> controls. The code in the Page_Load method sets the text displayed in the Welcome1 <span> element using the innerText property, so HTML-encoding is unnecessary. The code sets the text in the Welcome2 <span> element by using the innerHtml property; therefore, you must HtmlEncode it first to make it safe.

<%@ Page Language="C#" AutoEventWireup="true"%>
<html>
  <body>
    <span id="Welcome1" runat="server"> </span>
    <span id="Welcome2" runat="server"> </span>
  </body>
</html>

<script runat="server">
  private void Page_Load(Object Src, EventArgs e)
  {
    // Using InnerText renders the content safe-no need to HtmlEncode
    Welcome1.InnerText = "Hello, " + User.Identity.Name;

    // Using InnerHtml requires the use of HtmlEncode to make it safe
    Welcome2.InnerHtml = "Hello, " +
                        Server.HtmlEncode(User.Identity.Name);
  }
</Script>



ASP.NET 4.5 Hosting - How to Leverage the .NET 4.5 Model Binding and Strongly Typed Data Controls with Telerik’s ASP.NET AJAX Controls

clock May 15, 2013 10:58 by author Ben

The new release of RadControls for ASP.NET AJAX includes a ton of great new features and capabilities. This post is the second of two posts I will do over the week that elaborates on the new ModelBinding support and Strongly Typed Data Controls into the Telerik’s Ajax suite. In the previous part you learned how the Strongly Typed Data Controls work and how to select data and bind the controls via the ModelBinding capabilities available in .NET 4.5. Now you will learn how to do filtering, perform CRUD operations and validate user input when you use ModelBinding.

 

Model Binding Filtering
In order to filter the data source of the data bound control and pass the filtered data to the control you could pass filter parameters to use the SelectMethod. You could get these parameters from query string, cookies, form values, controls, viewstate, session and profile. For example:

public IQueryable<Product> GetProducts([Control("RadComboBoxCategories")] int? categoryID, [QueryString]string name)
{
    // Filter the data source based on categoryID and ProductName
}

The code snippet above will get the name parameter from the QueryString and integer value of the selected item of the Telerik’s ASP.NET ComboBox with ID equlas to “RadComboBoxCategories”.

Model Binding CRUD operations
Editing
In order to have editing enabled into the data bound controls, you need to set the UpdateMethod of the corresponding control to the web form page’s method. The UpdateMethod can have following signature:

public void UpdateProduct(int ProductID)
{
    Product updatedProduct = context.Products.Where(p => p.ProductID == ProductID).First();
   TryUpdateModel(updatedProduct);
   if (ModelState.IsValid)
   {
       context.SubmitChanges();
   }
}

Where the “ProductID” is one of the fields set as DataKeyNames of the corresponding bound control. 
Or you could use following signature:

public void UpdateProduct(Product product)
{
    Product updatedProduct = context.Products.Where(p => p.ProductID == product.ProductID).First();
    TryUpdateModel(updatedProduct);
    if (ModelState.IsValid)
    {
         context.SubmitChanges();
    }
}

Inserting
In order to have inserting enabled into the data bound controls you need to set the InsertMethod property of the corresponding control to the name of the web form page’s insert method. The InsertMethod can have following signatures:

public void InsertProduct(Product p)
{
     if (ModelState.IsValid)
     {
      context.Products.InsertOnSubmit(p);
      context.SubmitChanges();
     }
}

//OR

public void InsertProduct()
{
   Product pr = new Product();
   TryUpdateModel(pr);

    if (ModelState.IsValid)
    {
                context.Products.InsertOnSubmit(pr);
               context.SubmitChanges();
    }
}

Deleting
In order to have deleting enabled into the data bound controls you need to set the DeleteMethod property of the corresponding control to the name of the web form page’s delete method. The DeleteMethod can have following signature:

public void DeleteProduct(int ProductID)
{
   Product deletedProduct = context.Products.Where(p => p.ProductID ==
ProductID).First();
    context.Products.DeleteOnSubmit(deletedProduct);
    context.SubmitChanges();
}

ModelBinding Validation
Due to the fact that Model Binding system in Web Forms supports model validation using the same validation attributes from the System.ComponentModel.DataAnnotations you could use validation into our databound controls. You could decorate properties from your model classes with the attributes provided in System.ComponentModel.DataAnnotations namespace. For example if you have DataContext mapped to a Northwind database “Product” table and you want to ensure that when inserting new product or update existing one the ProductName field is populated, you could set [Required] attribute to it into the DataClasses.designer.cs file:

[Required]
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_ProductName", DbType="NVarChar(40) NOT NULL", CanBeNull=false)]
public string ProductName
{
     get
     {
           return this._ProductName;
     }
     set
     {
           if ((this._ProductName != value))
           {
           this.OnProductNameChanging(value);
           this.SendPropertyChanging();
           this._ProductName = value;
           this.SendPropertyChanged("ProductName");
           this.OnProductNameChanged();
           }
      }

Then when values from databound control editors are submitted to the server the the Web Forms Model Binding system will track whether any of these validation rules are violated in the page's ModelState property.

public void InsertProduct(Product p)
{
     if (ModelState.IsValid)
     {
           context.Products.InsertOnSubmit(p);
           context.SubmitChanges();
     }
}

To show any validation errors you could use asp:ValidationSummary control or asp:ModelErrorMessage:

<asp:ValidationSummary runat="server" ID="ValidationSummary1" />

Please note that even the model binding is a powerful feature included into the bound controls there are still some limitation.

Conclusion
With Model Binding support into our controls developing new application is never be as easy as it is now.  Please do not hesitate to download the RadControls for ASP.NET AJAX and try the model binding feature.



Cheap ASP.NET 4.5 Hosting

We’re a company that works differently to most. Value is what we output and help our customers achieve, not how much money we put in the bank. It’s not because we are altruistic. It’s based on an even simpler principle. "Do good things, and good things will come to you".

Success for us is something that is continually experienced, not something that is reached. For us it is all about the experience – more than the journey. Life is a continual experience. We see the Internet as being an incredible amplifier to the experience of life for all of us. It can help humanity come together to explode in knowledge exploration and discussion. It is continual enlightenment of new ideas, experiences, and passions


Author Link

 photo ahp banner aspnet-01_zps87l92lcl.png

 

Corporate Address (Location)

ASPHostPortal
170 W 56th Street, Suite 121
New York, NY 10019
United States

Tag cloud

Sign in