预提交需要字段验证ASP .NET MVC

时间:2017-01-04 16:43:10

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

我的回复时间非常快,对第一个问题的评论很有帮助,所以我想我会在这里提出另一个问题。

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

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

我只能在提交后才能这样做。

以下是我的相关代码段....

查看代码

@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"));
    }
}

正如你可以从控制器那里看到的还有一点,但为了简单起见,我想专注于一个字段,名称。

2 个答案:

答案 0 :(得分: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/

答案 1 :(得分:-1)

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

Model.where("mycolumn1= ? AND mycolumn2= ?", demo_type_param, demo_tid_param).firs