2016-06-23 42 views
1

我的視圖有一個文本框(電子郵件)和一個提交按鈕。如何根據MVC5顯示多條驗證消息

@using (Html.BeginForm("FindMyDetail", "ResetPassword", FormMethod.Post, new { @class = "form-horizontal", role = "form" })) 
    { 
     @Html.AntiForgeryToken() 
     <h4>Enter your email.</h4> 

    @Html.ValidationSummary(false, "", new { @class = "alert alert-danger" }) 

@Html.ValidationMessageFor(m=>m.Email) 
<div class="form-group"> 
    @Html.LabelFor(m => m.Email, new { @class = "col-md-2 control-label" }) 
    <div class="col-md-10"> 
     @*@Html.TextBoxFor(m => m.Email, new { @class = "form-control", @value = @Html.DisplayFor(m => m.Email) })*@ 
     @Html.TextBoxFor(m => m.Email, true, htmlAttributes: new { @class = "form-control", placeholder = "Enter Email Id you used to register" }) 
    </div> 
</div> 
<div class="form-group"> 
    <div class="col-md-offset-2 col-md-10"> 

     <input type="submit" class="btn btn-default" value="Email Link" /> 

    </div> 
</div> 

}

我在MVC的Web應用程序的視圖顯示多個驗證消息。

案例1:顯示驗證消息,當文本框留空時輸入電子郵件ID。

案例2:如果電子郵件存在,提交按鈕會觸發郵件。如果郵件失敗(false),則應該發送電子郵件不存在的驗證消息。 點擊提交按鈕會觸發一個控制器,該控制器會觸發給定的電子郵件。如果succesfull我將返回成功信息有不同的看法一樣,我將返回相同的視圖(EmailLink視圖)

在asp.net web表單執行,這似乎很容易,但看起來很不同,很不解,因爲上午如何在MVC實現這個新的。

編輯:我需要它使用自定義驗證實現。不使用數據交替。

+0

這聽起來很基本的,所有應隨Visual Studio – JamieD77

+0

的MVC項目模板覆蓋我需要一個模型的自定義驗證消息。 –

+1

ModelState.AddModelError? –

回答

0

這樣做有兩個簡單的方法,您可以在客戶端或服務器端進行驗證。

客戶端

導入這個jQuery插件在你的頁面: http://ajax.aspnetcdn.com/ajax/jquery.validate/1.15.0/jquery.validate.min.js

並在您的JavaScript文件,你可以創建你想要的驗證,例如:

$(document).ready(function() { 
    $("#FindMyDetail").validate({ 
    rules: { 
     Email: { 
     required: true, 
     maxlength: 40, 
     email: true 
     } 
    }, 
    messages: { 
     Email: { 
     required: "We need your email address to contact you", 
     email: "Your email address must be in the format of [email protected]" 
     } 
    } 
    }); 
}); 

服務器端

您可以使用asp.net框架並讓它驗證您的模型。你有一些屬性來裝飾你的模型,如:

public class Person 
{ 
    public int ID { get; set; } 

    [Required] 
    [StringLength(40)] 
    public string Email { get; set; } 
} 

而在你的控制器的動作:

[HttpPost] 
public ActionResult Create(Person person) 
{ 
    if (ModelState.IsValid) 
    { 
     //foo 
     return RedirectToAction("Index"); 
    } 

    return View(person); 
} 
+0

我需要它是自定義驗證消息。 –

+0

剛剛編輯我的答案以顯示自定義消息的驗證。 – gnllucena