· ebook

[ASP.NET] Performing validation

Step 1: Decorate property with validation attribute

public class GuestResponse
        [Required(ErrorMessage = "Please enter your name")]
        public string Name { get; set; }
        [Required(ErrorMessage = "Please enter your email")]
        public string Email { get; set; }
        [Required(ErrorMessage = "Please enter your phone")]
        public string Phone { get; set; }
        [Required(ErrorMessage = "Please enter your answer")]
        public bool? WillAttend { get; set; }

Step 2: Add validation summary server control

<form id="rsvpform" runat="server">
        <strong><asp:ValidationSummary runat="server" 
ShowModelStateErrors="True" ID="validationSummary"/></strong>
            Your name:                       
...     </form>

Source: ASP.NET 4.5 Pro Apress – Chapter 1


Advertisements · ebook

[ASP.NET] Calling a code-behind method

We can call a code behind method by using server-side evaluation syntax <%=.


In code behind, we have:

protected string GetYes()
            var yesData = ResponseRepository.GetRepository().GetAllResponses()
                .Where(r => r.WillAttend.HasValue && r.WillAttend.Value);
            var html = new StringBuilder();
            foreach (var rsvp in yesData)
            return html.ToString();         

We can get the string value from aspx by following syntax in aspx:

<form id="form1" runat="server">
        <h2>RSVP Summary</h2>

        <h3>People who will attend:</h3>
                <strong><%= GetYes() %></strong>

Source: ASP.NET 4.5 Pro Apress – Chapter 1 · ebook

[ASP.NET] TryUpdateModel and FormValueProvider

1. TryUpdateModel

TryUpdateModel method: perform a process called model binding where data value are used from the browser request to populate property of our data object. FormValueProvider class will provides value from form data.


protected void Page_Load(object sender, EventArgs e)
            if (!IsPostBack) return;
            var rsvp = new GuestResponse();
            if (!TryUpdateModel(rsvp, new FormValueProvider(ModelBindingExecutionContext))) return;
            if (rsvp.WillAttend.HasValue && rsvp.WillAttend.Value)

Source: ASP.NET 4.5 Pro Apress – Chapter 1