无法从局部视图中看到验证错误

时间:2016-03-22 19:07:47

标签: c# asp.net-core

包含一个包含表单的部分视图,但似乎无法显示验证错误。

模型

public class HomeModel
{
    public LoginModel LoginModel { get; set; }
}

public class LoginModel
{
    [Required]
    [Display(Name = "Email")]
    public string Username { get; set; }

    [Required]
    public string Password { get; set; }
}

Index.cshtml:

@model MyApp.Models.HomeModel

@{                
    await Html.RenderPartialAsync("_LoginPartial", Model.LoginModel);
}

的HomeController

public IActionResult Index()
{
    return View(new HomeModel()
    {
        LoginModel = new LoginModel()
    });
}        

[HttpPost]
public IActionResult Login(LoginModel model)
{
    return View("Index", new HomeModel()
    {
        LoginModel = model
    });
}

_LoginPartial

@model MyApp.Models.LoginModel
<form asp-action="Login" asp-controller="Home" method="post" role="form" style="width:70%;margin: 0 auto;">
    <div style="display:none" asp-validation-summary="ValidationSummary.All" class="alert alert-danger fade in">
        <a href="#" class="close" data-dismiss="alert">&times;</a>
        <strong>Error!</strong> A problem has been occurred while submitting your data.
    </div>
    <div class="form-group" style="text-align:left">
        <label asp-for="Username" style="font-size:22px;" class="control-label"></label>
        <input asp-for="Username" type="text" class="form-control" />
    </div>
    <div class="form-group" style="text-align:left">
        <label asp-for="Password" style="font-size:22px;" class="control-label"></label>
        <input asp-for="Password" type="password" class="form-control" />
    </div>
    <div class="spacer-15"></div>
    <div class="form-group" style="font-size:22px;">
        <button type="submit"
                style="background-color: Transparent;
                        background-repeat:no-repeat;
                        border: none;
                        cursor:pointer;
                        overflow: hidden;
                        outline:none;" value="Login">
            <img src="~/images/flower.png" />Next
        </button>
    </div>
</form>

1 个答案:

答案 0 :(得分:0)

看起来你错过了一些东西。您的每个输入都需要一个使用asp-validation-for的相应验证元素。

<div class="form-group" style="text-align:left">
    <label asp-for="Username" style="font-size:22px;" class="control-label"></label>
    <input asp-for="Username" type="text" class="form-control" />
    <span asp-validation-for="Username" class="text-danger"></span>
</div>

同样,如果您计划使用jQuery验证,则应将以下内容添加到_Layout.cshtml文件中的环境元素中。

<script src="~/lib/jquery-validation/dist/jquery.validate.js"></script>
<script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.js"></script>