Cao Con MVC 3

  1. HTML HELPERS
    HTML helpers are methods you can invoke on the Html property of a view. You also have access to URL helpers (via the Url property), and AJAX helpers (via the Ajax property). All these helpers have the same goal: to make views easy to author.
  2. Html.BeginForm
    The version of BeginForm in the preceding code,with no parameters, sends an HTTP POST to the current URL
  3. ValidationSummary helper
    The ValidationSummary helper displays an unordered list of all validation errors in the ModelState dictionary. The Boolean parameter you are using (with a value of true) is telling the helper to exclude property-level errors
  4. TextBox helper
    The TextBox helper renders an input tag with the type attribute set to text. You commonly use the TextBox helper to accept free-form input from a user

    @Html.TextBox(“Title”, Model.Title)

    results in:

    • <input id=”Title” name=”Title” type=”text”
    • value=”For Those About To Rock We Salute You” />
  5. Label helper
    The Label helper returns a <label/> element using the string parameter to determine the rendered text and for attribute value.

    <label for=”GenreId”>Genre</label>
  6. DropDownList and ListBox helpers
    Both the DropDownList and ListBox helpers return a <select /> element. DropDownList allows single item selection, whereas ListBox allows for multiple item selection (by setting the multiple attribute to multiple in the rendered markup).





    • public ActionResult Edit(int id)
    • {

    var album = storeDB.Albums.Single(a =>a.AlbumId == id);

    ViewBag.Genres = new SelectList(storeDB.Genres.OrderBy(g => g.Name), ”GenreId”, ”Name”, album.GenreId);

    • return View(album);
    • }
  7. ValidationMessage helper
    • When there is an error for a particular field in the ModelState dictionary, you can use the
    • ValidationMessage helper to display that message.


    @Html.ValidationMessage(“Title”)
  8. Strongly-Typed Helpers
    • With the strongly-typed helpers you pass a lambda expression to specify a model property for rendering. The model type for the expression will
    • be the same as the model specified for the view (with the @model directive)

    • @using (Html.BeginForm())
    • {

    • @Html.ValidationSummary(excludePropertyErrors: true)
    • <fieldset>

    • <legend>Edit Album</legend>
    • <p>

    @Html.LabelFor(m => m.GenreId)

    • @Html.DropDownListFor(m => m.GenreId, ViewBag.Genres as SelectList)
    • </p>

    • <p>
    • @Html.TextBoxFor(m => m.Title)
    • @Html.ValidationMessageFor(m => m.Title)

    </p>

    • <input type=”submit” value=”Save” />
    • </fieldset>

    }
  9. Templated Helpers
    • The templated helpers in ASP.NET MVC build HTML using metadata and a template. The meta-
    • data includes information about a model value (its name and type), as well as model metadata (added through data annotations). The templated helpers are Html.Display and Html.Editor (and
    • their strongly-typed counterparts are Html.DisplayFor and Html.EditorFor, respectively).
  10. Html.Hidden
    • The Html.Hidden helper renders a hidden input. For example, the following code:
    • @Html.Hidden(“wizardStep”, “1”)

    results in:

    <input id=”wizardStep” name=”wizardStep” type=”hidden” value=”1” />
  11. Html.Password
    The Html.Password helper renders a password field. It’s much like the TextBox helper, except that it does not retain the posted value, and it uses a password mask. The following code:

    @Html.Password(“UserPassword”)

    results in:

    <input id=”UserPassword” name=”UserPassword” type=”password” value=”” />
  12. Html.RadioButton
    • Radio buttons are generally grouped together to provide a range of possible options for a single
    • value. For example, if you want the user to select a color from a specific list of colors, you can use multiple radio buttons to present the choices. To group the radio buttons, you give each button the same name. Only the selected radio button is posted back to the server when the form is
    • submitted.

    The Html.RadioButton helper renders a simple radio button:

    • @Html.RadioButton(“color”, “red”)
    • @Html.RadioButton(“color”, “blue”, true)
    • @Html.RadioButton(“color”, “green”)
  13. Html.CheckBox
    The CheckBox helper is unique because it renders two input elements. Take the following code, for example:

    @Html.CheckBox(“IsDiscounted”)
  14. Html.ActionLink and Html.RouteLink
    The ActionLink method renders a hyperlink (anchor tag) to another controller action. Like the BeginForm helper you looked at earlier, the ActionLink helper uses the routing API under the hood to generate the URL. For example, when linking to an action in the same controller used to render the current view, you can simply specify the action name:

    @Html.ActionLink(“Link Text”, “AnotherAction”)
  15. RouteLink helper
    The RouteLink helper follows the same pattern as the ActionLink helper, but also accepts a route name and does not have arguments for controller name and action name. For example, the first example ActionLink shown previously is equivalent to the following:

    @Html.RouteLink(“Link Text”, new {action=”AnotherAction”})
  16. URL Helpers
    The URL helpers are similar to the HTML ActionLink and RouteLink helpers, but instead of returning HTML they build URLs and return the URLs as strings. There are three helpers:


    • Action
    • Content
    • RouteUrl
  17. Html.Partial
    The Partial helper renders a partial view into a string. Typically, a partial view contains reusable markup you want to render from inside multiple different views. Partial has four overloads:

    • public void Partial(string partialViewName);
    • public void Partial(string partialViewName, object model);
    • public void Partial(string partialViewName, ViewDataDictionary viewData);
    • public void Partial(string partialViewName, object model, ViewDataDictionary viewData);
  18. Html.Action and Html.RenderAction
    Action and RenderAction are similar to the Partial and RenderPartial helpers. The Partial helper typically helps a view render a portion of a view’s model using view markup in a separate file. Action, on the other hand, executes a separate controller action and displays the results. Action offers more flexibility and re-use, because the controller action can build a different model and make use of a separate controller context.
  19. Validation Annotations- Required
    Because you need the customer to give you his first and last name, you can decorate the FirstName and LastName properties of the Order model with the Required attribute:

    • [Required]
    • public string FirstName { get; set; }

    • [Required]
    • public string LastName { get; set; }
  20. Validation Annotations- StringLength
    .NET string type can store (in theory) gigabytes of Unicode characters, the MVC Music Store database schema sets the maximum length for a name at 160 characters. If you try to insert a larger name into the database, you’ll have an exception on your hands

    • [Required]
    • [StringLength(160)]
    • public string FirstName { get; set; }

    • [Required]
    • [StringLength(160)]
    • public string LastName { get; set; }
  21. Validation - RegularExpression
    Some properties of Order require more than a simple presence or length check. For example, you’d like to ensure the Email property of an Order contains a valid, working e-mail address. Unfortunately, it’s practically impossible to ensure an e-mail address is working without sending a mail message and waiting for a response. What you can do instead is ensure the value looks like a working e-mail address using a regular expression:

    • [RegularExpression(@”[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}”)]
    • public string Email { get; set; }
  22. Validation -Range
    The Range attribute specifies minimum and maximum constraints for a numerical value.

    • [Range(35,44)]
    • public int Age { get; set; }
  23. Validation Attributes from System.Web.Mvc
    The Remote attribute enables you to perform client-side validation with a server callback.
  24. Validation - Remote
    The Remote attribute enables you to perform client-side validation with a server callback.

    • [Remote(“CheckUserName”, “Account”)]
    • public string UserName { get; set; }
  25. Validation - Compare
    • Compare ensures two properties on a model object have the same value. For example, you might want to force a customer to enter his e-mail address
    • twice to ensure he didn’t make a typographical error:

    • [RegularExpression(@”[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}”)]
    • public string Email { get; set; }

    • [Compare(“Email”)]
    • public string EmailConfirm { get; set; }
  26. Custom Error Messages and Localization
    ErrorMessage is the name of the parameter in every validation attribute.

    • [Required(ErrorMessage=”Your last name is required”)]
    • [StringLength(160, ErrorMessage=”Your last name is too long”)]
    • public string LastName { get; set; }


    • [Required(ErrorMessage=”Your {0} is required.”)]
    • [StringLength(160, ErrorMessage=”{0} is too long.”)]
    • public string LastName { get; set; }
  27. Annotation -Display
    The Display attribute sets the friendly “display name” for a model property. You can use theDisplay attribute to fix the label for the FirstName field:

    • [Required]
    • [StringLength(160, MinimumLength=3)]
    • [Display(Name=”First Name”)]
    • public string FirstName { get; set; }
  28. Annotation - ScaffoldColumn
    The ScaffoldColumn attribute hides a property from HTML helpers such as EditorForModel and DisplayForModel:

    • [ScaffoldColumn(false)]
    • public string Username { get; set; }

    With the attribute in place, EditorForModel will no longer display an input or label for the Username field. Note however, the model binder might still try to move a value into the Username property if it sees a matching value in the request.
  29. Annotation - DisplayFormat
    The DisplayFormat attribute handles various formatting options for a property via named parameters. You can provide alternate text for display when the property contains a null value, and turn off HTML encoding for properties containing markup. You can also specify a data format string for the runtime to apply to the property value. In the following code you format the Total property of a model as a currency value:

    • [DisplayFormat(ApplyFormatInEditMode=true, DataFormatString=”{0:c}”)]
    • public decimal Total { get; set; }
  30. Annotation - ReadOnly
    Place the ReadOnly attribute on a property if you want to make sure the default model binder does not set the property with a new value from the request:

    • [ReadOnly(true)]
    • public decimal Total { get; set; }

    Note the EditorForModel helper will still display an enabled input for the property, so only the model binder respects the ReadOnly attribute.
Author
caocon
ID
110590
Card Set
Cao Con MVC 3
Description
Learning MVC3
Updated