2016年11月30日 星期三

TagHelper不顯示伺服端驗證錯誤訊息

 

Tool:Visual Studio 2015 Ultimate Update 3
OS:Windows 10
.NET Core  1.0.0
ASP.NET Core 1.0.0

問題:在文字方塊後使用asp-validation-for進行驗證:

<span asp-validation-for="Id"/>

但在asp-validation-for在伺服端驗證發生錯誤時,不會顯示錯誤訊息:

image

問題重現:

假設有Models定義如下:

public class Employee
{
    [DisplayName("員工編號")]
    public int Id { get; set; }
    [DisplayName("員工名稱")]
    [Required(ErrorMessage = "不可為空白")]
    public string Name { get; set; }
}

Controller包含以下程式

public class EmployeesController : Controller
{
    public IActionResult Create()
    {
        return View();
    }
    [HttpPost]
    public IActionResult Create(Employee emp)
    {
        if (ModelState.IsValid)
        {
            //Save to db
        }
        return View(emp);
    }
}

Create View如下

@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

@model CoreWebSample.Models.Employee

<form asp-action="Create">
    <fieldset>
        <legend>Employees</legend>
        <div asp-validation-summary="All"></div>
        <div>
            <label asp-for="Id"></label>
            <input asp-for="Id" />
            <span asp-validation-for="Id"/>
        </div>
        <div>
            <label asp-for="Name"></label>
            <input asp-for="Name" />
            <span asp-validation-for="Name"/>
        </div>

        <div>
            <div>
                <input type="submit" value="Create" />
            </div>
        </div>
    </fieldset>
</form>

執行時驗證發生錯誤asp-validation-summary顯示了錯誤訊息,但asp-validation-for卻不顯示錯誤訊息:

image

解法:

修改View,套用asp-validation-for Attribute的HTML Element開頭和結尾的標籤應該要分開寫,就像套用asp-validation-summary的標籤一樣:

@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

@model CoreWebSample.Models.Employee

<form asp-action="Create">
    <fieldset>
        <legend>Employees</legend>
        <div asp-validation-summary="All"></div>
        <div>
            <label asp-for="Id"></label>
            <input asp-for="Id" />
            <span asp-validation-for="Id"></span>
        </div>
        <div>
            <label asp-for="Name"></label>
            <input asp-for="Name" />
            <span asp-validation-for="Name"></span>
        </div>

        <div >
            <div>
                <input type="submit" value="Create" />
            </div>
        </div>
    </fieldset>
</form>

如此驗證訊息就會正確的呈現了:

image

沒有留言:

總網頁瀏覽量