该问题已经指出了问题的一半,这似乎是一个极其繁重的框架错误,即:当您的视图模型具有Title
属性时,绑定到该属性会使客户端验证失败工作:
Html.TextBoxFor(m => m.Title)
结果input
标签中没有任何验证属性,这似乎也使其余客户端验证也因其他属性而失败(我对此有90%的把握)。
问题:
是否有人记录了这个长期运行的错误?
这是怎么回事?重要的是,这仅在其他某些条件成立时才发生吗?我觉得该框架将ViewBag.Title
与您自己的视图模型的Title
属性混淆了。
应该采取什么措施缓解这一问题?
简短地获得这些答案,仅知道这可能是客户端验证失败的原因之一,这是胜利,就我而言,这只是偷走了一天半的时间,直到我将事情缩小到此奇异的Title
属性。但很想听听特别是上述前两个问题的答案。至于#3)
为缓解该问题,一种解决方案是不使用该属性,而将该属性命名为Title2
。而且,如果使用映射器,您仍然可以添加一个Title
属性,该属性从此辅助Title2
字段获取并设置,这对我有用,例如:
public string Title { get => Title2; set { Title2 = value; } }
---编辑---
以下是一个最小的示例。我没有时间去做一个完整的项目或复制所有内容。我不知道,我正在从事的大型项目(全框架MVC 5.2.6)中的某些设置当然有可能导致某些事情最终导致这种情况。但这总比没有好。如果您绑定到Title
,它将失败,然后绑定到Title2
,它将起作用:
FooVM
:public class FooVM
{
[Required]
[StringLength(64)]
public string Title2 { get; set; }
public string Title { get; set; }
// fix with this: public string Title { get => Title2; set { Title2 = value; } }
[Required]
[StringLength(256)]
public string Body { get; set; }
[Range(1, 100_000_000)]
[Required]
public int FooId { get; set; }
public int OrgId { get; set; }
}
@model FooVM
@{
ViewBag.Title = "Foo!";
string msg = ViewBag.Message ?? "";
// you can test it out directly here if you want:
//string str2 = Html.TextBoxFor(m => m.Title).ToHtmlString();
}
<div class="pagetile">
<div class="row-fluid">
<div class="span12">
<h2>Yo dog, why you not workin'?</h2>
<p> @msg.ToHtmlString() </p>
@using (Html.BeginForm()) {
@Html.ValidationSummary()
@Html.HiddenFor(m => m.FooId)
@Html.HiddenFor(m => m.OrgId)
<div>
Title:
@Html.TextBoxFor(m => m.Title) @*change to Title2 and it works*@
@*
you can do this manually as well, both helpers fail to produce the validation tags on the generated input element:
@Html.TextBox("Title", "", null, null)
*@
@Html.ValidationMessageFor(model => model.Title) @*this part is always fine*@
</div>
<button type="submit">Submit</button>
}
</div>
</div>
</div>
public class FooController
{
public async Task<ActionResult> Foo()
{
return View(new FooVM());
}
[HttpPost]
public async Task<ActionResult> Foo(FooVM vm)
{
if (!ModelState.IsValid) {
ViewBag.Message = $"Not valid!";
return View(vm);
}
ViewBag.Message = "Cool beans";
return View(vm);
}
}
绑定到Title
时,它将生成以下html:
<input id="Title" name="Title" type="text" value="">
绑定到Title2
会生成以下内容:
<input data-val="true" data-val-length="The field Title2 must be a string with a maximum length of 64." data-val-length-max="64" data-val-required="The Title2 field is required." id="Title2" name="Title2" type="text" value="">