asp.net · 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

 

asp.net · ebook

[ASP.NET] Calling a code-behind method

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

Example:

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)
            {
                html.Append($"{rsvp.Name}{rsvp.Email}{rsvp.Phone}");
            }             
            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>
        <table>
            <thead>
                <tr>
                    <th>Name</th>
                    <th>Email</th>
                    <th>Phone</th>
                </tr>
            </thead>
            <tbody>
                <strong><%= GetYes() %></strong>
            </tbody>
        </table>
    </form>

Source: ASP.NET 4.5 Pro Apress – Chapter 1

 

asp.net · 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.

Example:

protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack) return;
 
            var rsvp = new GuestResponse();
 
            if (!TryUpdateModel(rsvp, new FormValueProvider(ModelBindingExecutionContext))) return;
 
            ResponseRepository.GetRepository().AddResponse(rsvp);
 
            if (rsvp.WillAttend.HasValue && rsvp.WillAttend.Value)
                Response.Redirect("seeyouthere.html");
            else
                Response.Redirect("sorryyoucantcome.html");
        }

Source: ASP.NET 4.5 Pro Apress – Chapter 1