我正在使用 FluentValidation 表单,并且验证摘要似乎在加载时显示。我没有任何似乎可以自动提交表单的东西,并且在我的控制器中,在发布表单之前不会进行验证检查。很奇怪,提交时验证似乎工作得很好。
视图模型:
[Validator(typeof(SendMessageInputValidator))]
public class SendMessageInput
{
public string Title { get; set; }
public string Content { get; set; }
public string VideoUrl { get; set; }
public string CultureName { get; set; }
public bool VideoMode { get; set; }
}
public class SendMessageInputValidator : AbstractValidator<SendMessageInput>
{
public SendMessageInputValidator()
{
RuleFor(s => s.Title)
.NotEmpty().WithMessage("TitleRequired".Translate("MCN"));
}
}
控制器:
public ActionResult Detail(Guid entityId, string cultureName)
{
var entity = _sendMessageRepository.Get(entityId);
if (entity == null)
throw new HttpException(404, "Not found.");
return View(new SendMessagePageViewModel
{
NodeId = entity.NodeId,
Name = entity.Name,
Title = entity.Title,
Content = entity.Content,
BrowserTitle = entity.BrowserTitle,
MetaDescription = entity.MetaDescription,
MetaKeywords = entity.MetaKeywords,
SendMessageInput = new SendMessageInput { VideoMode = true }
});
}
public ActionResult SendMessageForm(SendMessageInput input)
{
input.CultureName = Thread.CurrentThread.CurrentUICulture.Name;
return PartialView(/*input*/ new SendMessageInput());
}
[HttpPost]
public ActionResult SendMessage(SendMessageInput input)
{
Thread.CurrentThread.CurrentUICulture = new CultureInfo(input.CultureName);
if (ModelState.IsValid)
{
return Redirect(Utilities.GetUrl(Constants.NodeIds.MyProfile));
}
var entity = _sendMessageRepository.Get(Constants.NodeIds.MentorQuestionForm);
if (entity == null)
throw new HttpException(404, "Not found.");
return PartialView("Detail", new SendMessagePageViewModel
{
NodeId = entity.NodeId,
Name = entity.Name,
Title = entity.Title,
Content = entity.Content,
BrowserTitle = entity.BrowserTitle,
MetaDescription = entity.MetaDescription,
MetaKeywords = entity.MetaKeywords,
SendMessageInput = input
});
}
视图(主要):
@Html.Action("SendMessageForm", "SendMessage", Model.SendMessageInput)
查看(部分):
@Html.ValidationSummary(false, "ValidationSummaryHeader".Translate("MCN"))
@using (Html.BeginForm("SendMessage", "SendMessage", FormMethod.Post))
{
<div class="Formulaire">
<p>
@Html.LabelFor(m => m.Title, "Title".Translate("MCN"), true)
@Html.TextBoxFor(m => m.Title, new { maxlength = 200, @class = "TxtBox" })
</p>
@if (Model.VideoMode)
{
<p>
@Html.LabelFor(m => m.VideoUrl, "VideoUrl".Translate("MCN"))
@Html.TextBoxFor(m => m.VideoUrl)
</p>
}
else
{
<p>
@Html.LabelFor(m => m.Content, "Message".Translate("MCN"))
@Html.TextAreaFor(m => m.Content, new { @class = "TxtArea" })
</p>
}
@Html.HiddenFor(m => m.CultureName)
<input type="submit" value="@("Submit".Translate("MCN"))"/>
</div>
}