【问题标题】:Pre submission required field validation ASP .NET MVC预提交必填字段验证 ASP .NET MVC
【发布时间】:2017-05-19 01:15:17
【问题描述】:

我的响应时间如此之快,并且对我的第一个问题很有帮助,所以我想我会在这里提出另一个问题。

目前我有一个进行表单验证的应用程序。我的问题是它仅在提交后显示必填字段或表单验证。但是我希望它在它旁边显示一个星号或验证消息,直到有一些文本或满足验证要求。

因此,当您转到空白表单时,所有必填字段都应该有一条消息或星号,当我键入或满足字段要求时,该消息应该消失。

我只能在提交后让它这样做。

这是我的相关代码sn-ps....

查看代码

@using (Html.BeginForm("Register", "Account", FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
{
    @Html.AntiForgeryToken()
    <h4>Create a new account.</h4>
    <hr />
   // @Html.ValidationSummary("", new { @class = "text-danger" })

    <div class="form-group">
        @Html.LabelFor(m => m.FirstName, new { @class = "col-md-2 control-label" })
        <div class="col-md-10">
            @Html.TextBoxFor(m => m.FirstName, new { @class = "form-control" })
            @Html.ValidationMessageFor(m => m.FirstName)
        </div>
    </div>
}
@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

控制器代码

[AllowAnonymous]
public ActionResult Register()
{   
    return View();
}

//
// POST: /Account/Register
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Register(RegisterViewModel model)
{
    if (ModelState.IsValid)
    {
        var user = new ApplicationUser { UserName = model.Email, Email = model.Email, FirstName = model.FirstName,
        LastName = model.LastName, PhoneNumber = model.PhoneNumber};
        var result = await UserManager.CreateAsync(user, model.Password);

        if (result.Succeeded)
        {
            await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);

            // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
            // Send an email with this link
            // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
            // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
            // await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");

            return RedirectToAction("Index", "Home");
        }
        AddErrors(result);
    }

    // If we got this far, something failed, redisplay form
    return View(model);
}

型号代码

public class RegisterViewModel
{
    [Required]
    public string FirstName { get; set; }
}

网页配置代码

        <appSettings>
    <add key="webpages:Version" value="3.0.0.0" />
    <add key="webpages:Enabled" value="false" />
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
    <add key="vs:EnableBrowserLink" value="false" />
  </appSettings>

捆绑配置代码

public class BundleConfig
{
    // For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862
    public static void RegisterBundles(BundleCollection bundles)
    {
        bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                    "~/Scripts/jquery-{version}.js"));

        bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
                    "~/Scripts/jquery.validate*"));

        // Use the development version of Modernizr to develop with and learn from. Then, when you're
        // ready for production, use the build tool at http://modernizr.com to pick only the tests you need.
        bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
                    "~/Scripts/modernizr-*"));

        bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
                  "~/Scripts/bootstrap.js",
                  "~/Scripts/respond.js"));

        bundles.Add(new StyleBundle("~/Content/css").Include(
                  "~/Content/bootstrap.css",
                  "~/Content/site.css"));
    }
}

正如您从控制器中看到的那样,还有更多工作要做,但为简单起见,我只想关注一个字段,即名称。

【问题讨论】:

  • 是否启用客户端验证?
  • @KimHoang 是的,我开启了客户端验证。我将更新我的问题。

标签: jquery asp.net asp.net-mvc forms validation


【解决方案1】:

你需要使用不显眼的估值

1) 通过 nuget 安装:
https://www.nuget.org/packages/jQuery.Validation.Unobtrusive/ 这将在我们的 Scripts 目录中安装一堆 javascript 文件

2) 编辑你的 bundleConfig

public static void RegisterBundles(BundleCollection bundles)  
{
    bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                "~/Scripts/jquery-{version}.js"));

    bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
                "~/Scripts/jquery.validate*"));
}

3) 您需要在页面上的某处呈现不显眼的脚本,如下所示:

@Scripts.Render("~/bundles/jqueryval")

这应该让你开始。

有关如何执行此操作的完整指南在这里:

https://www.exceptionnotfound.net/asp-net-mvc-demystified-unobtrusive-validation/

【讨论】:

  • 这看起来很有希望,谢谢,午饭后我会测试一下。
  • 回到它,我刚刚通读了这篇文章,我已经有了所有的设置......
  • 我已经决定这是尽可能接近的,无需更多代码。它确实会立即为您提供验证,但仅在第一次提交之后。因此,如果您提交一个空表单,那么所有消息都会实时与您作出反应,但这取决于第一次提交。
【解决方案2】:

客户端验证是使用 jquery 完成的。确保您的页面中包含 jquery 和验证脚本。

<script src=".../Scripts/jquery.validate.js"></script>
<script src=".../Scripts/jquery.validate.unobtrusive.js"></script>

【讨论】:

  • 这不是做所有的工作吗?您仍然必须按照说不的方式做一些事情?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-07
  • 1970-01-01
  • 2014-03-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多