1

MVC4 アプリには、ビュー モデルとして継承するビジネス オブジェクトがいくつかあります。DataAnnotationsビジネスオブジェクトで指定するのではなく、ビューモデルで使いたい。それは可能ですか?

ビジネス オブジェクト

 public class Country
    {
        [Display(Name = "Country")]
        public virtual int CountryId { get; set; }
        public virtual string CountryName { get; set; }
        public virtual string CountryCode { get; set; }
    }

    public class State : Country
    {
        [Display(Name = "State")]
        public virtual int StateId { get; set; }
        public virtual string StateName { get; set; }
        public virtual string StateCode { get; set; }
    }

    public class City : State
    {
        public virtual int CityId { get; set; }

        [Display(Name = "City")]
        public virtual string CityName { get; set; }
    }

モデルを見る

public class Regional
{
    public Regional()
    {
        Countries = new Collection<Country>();
        States = new Collection<State>();
        City = new City();
    }
    public Collection<Country> Countries { get; set; }

    public Collection<State> States { get; set; }

    [Required(ErrorMessage = "Required")]
    public City City { get; set; }
}

上記のコードでは、City Property のデータ注釈を使用しています。

  1. ここで直面している問題は、この必須の注釈がなくても、国と州についてはフォームが検証されますが、都市名については検証されないことです。
  2. 必要な注釈を追加すると、国と州のみが検証され、都市名は検証されません。

何か案は?

私の見解

@using (Html.BeginForm(Actions.AddCity, Controllers.AdminUtility, FormMethod.Post))
{
    <div class="alert-error">
        @Html.ValidationSummary()
    </div>
    <div class="row-fluid">
        <fieldset class="form-horizontal">
            <legend class="header">Add City</legend>
            <div class="control-group">
                @Html.LabelFor(m => m.City.CountryId, new { @class = "control-label" })
                <div class="controls">
                    @Html.DropDownListFor(m => m.City.CountryId, new SelectList(Model.Countries, "CountryId", "CountryName"),"", new { @class = "chosen", data_placeholder = "Choose Country..." })
                </div>
            </div>
            <div class="control-group">
                @Html.LabelFor(m => m.City.StateId, new { @class = "control-label" })
                <div class="controls">
                    @Html.DropDownListFor(m => m.City.StateId,new SelectList(Model.States, "StateId","StateName"), "",new { @class = "chosen", data_placeholder = "Choose State..." })
                </div>
            </div>
            <div class="control-group">
                @Html.LabelFor(m => m.City.CityName, new { @class = "control-label" })
                <div class="controls">
                    @Html.TextBoxFor(m => m.City.CityName)
                </div>
            </div>
            <div class="control-group">
                <div class="controls">
                    <input type="submit" />
                </div>
            </div>
        </fieldset>
    </div>
}
4

1 に答える 1