我正在使用tuples
將多個模型加載到視圖中。未顯示ASP.NET MVC驗證錯誤
的視圖是爲
@using (Ajax.BeginForm(null, null, ajaxOptions, new { @class = "contact-form" }))
{
@Html.AntiForgeryToken()
<div class="form-group form-group--xs">
@Html.TextBoxFor(m => m.Item2.Email, new { @class = "form-control input-sm", placeholder = "Your email address..." })
@Html.ValidationMessageFor(m => m.Item2.Email)
</div>
<div class="form-group form-group--xs">
@Html.TextAreaFor(m => m.Item2.Message, new { @class = "form-control input-sm", placeholder = "Your message...", rows = "4" })
@Html.ValidationMessageFor(m => m.Item2.Message)
</div>
<input type="submit" class="btn btn-primary-inverse btn-sm btn-block" value="Send Your Message" />
}
控制器是
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<PartialViewResult> Submit([Bind(Prefix = "Item2")] ContactForm model)
{
bool isMessageSent = true;
if (ModelState.IsValid)
{
try
{
await Services.EmailService.SendContactForm(model);
}
catch (Exception ex)
{
isMessageSent = false;
}
}
else
{
isMessageSent = false;
}
return PartialView("_SubmitMessage", isMessageSent);
}
和接觸形式是
public class ContactForm
{
[Required(ErrorMessage = "You must provide your email."), EmailAddress]
public string Email { get; set; }
[Required(ErrorMessage = "You must include a message.")]
public string Message { get; set; }
}
最後的局部視圖是
@model bool
@if (Model)
{
<div style="color:#c2ff1f">Your message has been sent.</div>
}
else
{
<div style="color:#f34141">An error occured while sending your message</div>
}
更新:的電子郵件文本呈現的HTML是
<input class="form-control input-sm"
data-val="true"
data-val-email="The Email field is not a valid e-mail address."
data-val-required="You must provide your email."
id="Item2_Email"
name="Item2.Email"
placeholder="Your email address..."
type="text"
value="">
如果我不輸入電子郵件字段或消息字段的任何文本,沒有發送消息:)但我沒有驗證在視圖中的錯誤:( 我在這裏做錯了什麼?
我不確定,但我認爲如果您返回視圖而不是偏視圖會更好。您將進入顯示發送錯誤信息的屏幕。我認爲這足夠當你插入「返回視圖();」在控制器的else塊中。 – Larce
@Larce更改爲公共異步任務並返回View(model);但它也沒有按預期工作 –
OrElse
發生了什麼呢?你還是會看到局部的觀點嗎? – Larce