Asp.Netmvc 2 in actionノート-4自動コード生成、検証Validation

5385 ワード

自動コード生成


T4 (Text Template Transformation Toolkit) is a little-known feature of Visual Studio. It’s a code-generation toolkit, and its templates allow us to customize how files are generated using a familiar syntax.

T4MVC


Out of the box, ASP.NET MVC contains many opportunities to get tripped up with magic strings, especially with URL generation. Magic strings are string constants that are used to represent other constructs, but with an added disconnect that can lead to subtle errors that only show up at runtime. To provide some intelligence around referencing controllers, views, and actions, the T4MVC project helps by generating a hierarchical code model representation for use inside controllers and views.
http://mvccontrib.codeplex.com/wikipage?title=T4MVC
■ T4MVC.tt
■ T4MVC.settings.t4
Html.ActionLink("Log On", "LogOn", "Account")
Html.ActionLink("Log On", MVC.Account.LogOn()
Html.ActionLink("Profile", MVC.Admin.Profile.Show(Html.Encode(Page.User.Identity.Name))

カスタムT 4テンプレート


www.visualt4.com/downloads.html Visual T 4 EditorはT 4を編集して確立することができるテンプレート
のように
C:\Program Files\Microsoft Visual Studio 10.0\Common7\IDE\ItemTemplates\CSharp\Web\MVC 2\CodeTemplates\AddController
コントローラの追加時
C:\Program Files\Microsoft Visual Studio 10.0\Common7\IDE\ItemTemplates\CSharp\Web\MVC 2\CodeTemplates\AddView
ビューを追加するときに使用すると、モデリングに基づいて必要なコードを自動的に生成し、手動入力を減らし、効率を高めることができます.
下のttファイルはすべてt 4に基づいて生成される

Validationの検証


サービス側

System.ComponentModel.DataAnnotations            

次の例
public class CompanyInput
{
    [Required]
    public string CompanyName { get; set; }
 
    [DataType(DataType.EmailAddress)]
    public string EmailAddress { get; set; }
}
コントローラプロセッサはModelStateをチェックする.IsValidは、次の例のように有効性を決定する.
  [HttpPost]
        public ActionResult Edit(CompanyInput input)
        {
            if (ModelState.IsValid)
            {
                return View("Success");
            }
            return View(new CompanyInput());
        }

クライアント


Microsft AJAXの方式:
  • は、まず、
  • を含む.
        <script src="http://www.cnblogs.com/Scripts/MicrosoftAjax.js" type="text/javascript"></script>
        <script src="http://www.cnblogs.com/Scripts/MicrosoftMvcAjax.js" type="text/javascript"></script>
        <script src="http://www.cnblogs.com/Scripts/MicrosoftMvcValidation.js" type="text/javascript"></script>
  • 検証が必要なページには、
  • が含まれます.
    <% Html.EnableClientValidation(); %>

    Client Validation


    <% Html.EnableClientValidation(); %>                               
    <% using (Html.BeginForm("Edit", "Home")) { %>                     
        <%= Html.EditorForModel() %>
       
    <% } %>
    The EnableClientValidation method merely turns on a flag in ViewContext. It’s the BeginForm form helper method that emits the pertinent client-side scripts to enable validation. The EnableClientValidation needs to be placed before the BeginForm method in your view to correctly enable scripts.
     In our original screen with company name and email address, the model metadata is emitted as a set of JSON objects. This JSON, shown in figure 15.5, includes the model metadata information, validation information, and model information in the form of a well-structured JSON object. The generated validation information combines with the MVC validation library to act as a bridge between the client-side validation framework and the server-side model metadata emitted as JSON. For example, we can see in figure 15.5 that there seems to be some information about the CompanyName field, as well as a validation message for the required field validation.
    ViewerのHelper関数は、Modelのメタデータ情報に基づいてクライアントの検証情報を生成する
    この方式はクライアント、サービス側の検証を効果的に統一した.
    上記の例では、クライアントのページコードを見ると、生成されたjavascriptコードが表示されます.

    //if (!window.mvcClientValidationMetadata) { window.mvcClientValidationMetadata = []; }
    window.mvcClientValidationMetadata.Push({"Fields":[{"FieldName":"CompanyName","R e p l a c e ValidationMessageContents":true,"ValidationMessageId":"CompanyName_validationMessage","ValidationRules":[{"ErrorMessage":"Company Nameフィールドが必要です.""ValidationParameters":{},"ValidationType":"required"}]},{"FieldName":"EmailAddress","ReplaceValidationMessageContents":true,"ValidationMessageId":"EmailAddress_validationMessage","ValidationRules":[]}],"FormId":"form0","ReplaceValidationSummary":false});
    //]]>