私は MVC が初めてで、適切な設計について確信が持てません。
さまざまなアプリケーションで使用するクラス オブジェクトがあります。これらすべてのオブジェクトのプロパティにアクセスし、厳密な型指定を行うことができるように、カスタム ビュー モデル クラスを作成するアプローチを取りました。ビュー モデルですべてのクラス コードを再入力せずに、データ注釈を使用してこれらのオブジェクトのプロパティを検証する方法はありますか? 私のアプローチとデザインがすべて間違っている場合はお知らせください。
[Required]
public User user = new User("username");
//User has lots properites and methods, could i validate inside my class code?
//避けたいのは、カスタム ビュー モデル クラスに次のものを入れることです。//このようなものを含むクラス ライブラリが既にあるからです。
public class User
{
[Required]
[StringLength(160)]
public string prop1 { get; set; }
[Required]
[StringLength(160)]
public string prop2 { get; set; }
[Required]
[StringLength(160)]
public string prop3 { get; set; }
public User(string token)
{
SetUser(token);
}
public void SetUser(string token)
{
this.prop1 = "this";
this.prop2 = "this2";
this.prop3 = "this3";
}
============ できるとわかってよかったのですが、いくつかの問題につまずいています。私の見解では: @Html.EditorFor(modelItem => modelItem.user.prop1)
クラスドメインにデータ注釈を入れました。レンダリングすると、注釈が表示されます。
<input class="text-box single-line" data-val="true" data-val-length="The field prop1 must be a string with a maximum length of 5." data-val-length-max="5" data-val-required="The prop1 field is required." id="user_prop1" name="user.prop1" type="text" value="somevalue" />
しかし、コントローラーに行くと、パラメーターはnullです。名前がuser.prop1だからだと思います。name 属性を指定したテキストボックスを試しましたが、コントローラーはまだパラメーターの値を取得できませんでした。
====================
@model TrainingCalendar.Models.Training
@{
ViewBag.Title = "Signup";
}
<h2>Signup</h2>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
@using (Html.BeginForm("ConfirmSignup", "Training", FormMethod.Post))
{
@Html.ValidationSummary(true)
<fieldset>
<legend>Training</legend>
<p>
@Html.Label("date", Model.SpecifiedCourse.strClassDate)
</p>
<p>
@Html.Label("time", Model.SpecifiedCourse.Time)
</p>
<p>
@Html.Label("instructor", Model.SpecifiedCourse.Instructor)
</p>
<p>
@Html.Hidden("id", Model.SpecifiedCourse.ID)
</p>
<table>
<tr>
<td>@Html.LabelFor(modelItem => modelItem.ApplicationUser.prop1)</td>
<td>@Html.EditorFor(modelItem => modelItem.ApplicationUser.prop1)</td>
<td style="color:Red">@Html.ValidationMessageFor(modelItem => modelItem.ApplicationUser.prop1)</td>
</tr>
<tr>
<td>@Html.LabelFor(modelItem => modelItem.ApplicationUser.prop2)</td>
<td>@Html.EditorFor(modelItem => modelItem.ApplicationUser.prop2)</td>
<td style="color:Red">@Html.ValidationMessageFor(modelItem => modelItem.ApplicationUser.prop2)</td>
</tr>
</table>
<p>
<input type="submit" value="Sign Up" />
</p>
</fieldset>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
===================
public ActionResult ConfirmSignup(
int id,
string prop1,
string prop2)
{
SignUpForClass();
return View();
}