0
我已经设置了一个小测试项目,我希望能解释我的问题。 我有一个父类,有一个属性包含其所有子类型的孩子。在MVC视图我列出所有的孩子在一个表中,并有表格后回我的孩子,并将它们映射到父属性自动我使他们像:jquery unobtrusive不发射验证属性客户端时,有一个子网格
@Html.TextBox(string.Format("Children[{0}].ChildName", childIndex), child.ChildName)
在我已标记属性ChildName控制器需要。我有的问题是,jQuery的不显眼的验证不会发出任何数据验证属性。一切都在服务器上验证,但在客户端上却不是很明显(显然是因为jQuery验证没有找到这些输入的属性)。
请看看代码:
VIEW
@{
Layout = "~/Views/Shared/_Layout.cshtml";
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<div>
<form action="@Url.Action("Save")" method="post">
@Html.TextBox("Name", (string)Model.Name)
<table>
<tr><td>Child name</td></tr>
@{var childIndex = 0;}
@foreach (var child in (List<GridValidationTest.Controllers.Child>)Model.Children)
{
<tr><td>@Html.TextBox(string.Format("Children[{0}].ChildName", childIndex), child.ChildName)</td></tr>
childIndex++;
}
</table>
<br /><button>Submit</button>
</form>
</div>
</body>
</html>
控制器
namespace GridValidationTest.Controllers
{
public class Parent
{
[Required]
public string Name { get; set; }
public IList<Child> Children { get; set; }
}
public class Child
{
[Required]
public string ChildName { get; set; }
}
public class MyController : Controller
{
//
// GET: /My/
public ActionResult Index()
{
var parent = new Parent { Name = "Parent name" };
parent.Children = new List<Child>
{
new Child {ChildName = "First child"},
new Child {ChildName = "Second child"}
};
return View("Index", parent);
}
public ActionResult Save(Parent parent)
{
return View("Index", parent);
}
}
}
于预期父类的属性名称正常工作的客户端验证。 我应该如何渲染孩子让客户端验证按我所期望的那样工作?
我立刻跑进了新的问题。我想我很快发现为什么我没有在我的原始项目中使用@ Html.TextBoxFor进行渲染。我的一些真实属性例如Timespan,我需要在视图中格式化输出,例如.ToString(“hh':'mm”)。这不适用于TextBoxFor。那我的下一步是什么? (我不得不接受你的答案,因为它是问的问题的正确解决方案) – John
没关系,想我找到了一个好帖子[这里](http://stackoverflow.com/questions/1961114/date-only-from- textboxfor) – John
很高兴我能帮忙;) –