我是MVC的新手,不确定正确的设计。类库,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();
}
什么参数为空?你在使用模型绑定吗? – GunnerL3510 2012-07-09 19:02:26
我正在尝试创建一个自定义模型联编程序。我一直没有能够得到它的工作。我的自定义视图模型类具有我自己创建的通用列表,2个字符串,1个int和2个对象:用户和培训课程。用户对象有一个设置值的方法,但是我已经将它移出构造函数。任何帮助表示赞赏。 – 2012-07-16 21:19:50
你可以发布你的POST(无双关意图)操作方法吗? – GunnerL3510 2012-07-17 19:42:01