简体   繁体   English

MVC4 验证不起作用

[英]MVC4 validation does not work

I have simple 1 page application to send email out to users.我有一个简单的 1 页应用程序来向用户发送电子邮件。 I have 3 fields for name, email and phone number.我有 3 个字段用于姓名、电子邮件和电话号码。 The code seems to work with input button, with validations firing and throwing proper error message.该代码似乎与输入按钮一起工作,验证触发并抛出正确的错误消息。 But I am more inclined towards using anchor tag (ActionLink) for my UI.但我更倾向于在我的 UI 中使用锚标记 (ActionLink)。 The data still posts when I click on anchor tag (using jQuery) but the validations don't fire.当我单击锚标记(使用 jQuery)时,数据仍然会发布,但不会触发验证。 Is there anything that I am missing or there's a better way of doing it?有什么我遗漏的或者有更好的方法吗?

I have used this post as reference.我用这篇文章作为参考。

Model模型

public class Contact
{
    [Required(ErrorMessage = "Name is required")]
    public string Name { get; set; }

    [Required(ErrorMessage = "Email is required")]
    public string Email { get; set; }

    [Required(ErrorMessage = "Phone is required")]
    public string PhoneNumber { get; set; }
}

View看法

            <div>
                @Html.TextBoxFor(model => model.Name, new { @class = "form-control", placeholder="Name" })
                @Html.ValidationMessageFor(model=>model.Name)
            </div>
            <div>
                @Html.TextBoxFor(model => model.Email, new { @class = "form-control", placeholder="Email" })
                @Html.ValidationMessageFor(model=>model.Email)
            </div>
            <div>
                @Html.TextBoxFor(model => model.PhoneNumber, new { @class = "form-control", placeholder="Phone" })
                @Html.ValidationMessageFor(model=>model.PhoneNumber)
            </div>
            <div>
                <input type="submit" value="Give me Free Advice" />
                <div class="btn">
                    @Html.ActionLink("I want free advice", "designerhome")
                </div>
            </div>
  <script>
    $(function () {
        $('.btn').click(function (e) {

            $.post("/campaign/designerhome", { Name: $("#Name").val(), Email: $("#Email").val(), PhoneNumber: $("#Phone").val() }, function (result) {
                //do whatever with the response
                if (result.status == true) {
                    alert('Email submitted successfully');
               }
            });//end of post
        });//end of click
    });
</script>

Controller控制器

[HttpPost]
    public ActionResult designerhome(Contact contact)
    {
        if (ModelState.IsValid)
        {
        }
        return View("Advert1");
    }

We have some reasons why validation not working我们有一些验证不起作用的原因

1. Check appsettings in web config 1. 检查 web 配置中的 appsettings

    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />

Both Should be true if you want to run client side validation.如果要运行客户端验证,则两者都应该为真。

2. Seems in your code you are not using Form tag as it is posted in the question 2. 似乎在您的代码中您没有使用 Form 标签,因为它是在问题中发布的

Form tag is must for validation表单标签必须用于验证

3. Jquery is not properly refrenced on layout page 3. 布局页面没有正确引用 Jquery

please check following jquery refrence on your layout page请检查您的布局页面上的以下 jquery 参考

jquery.unobtrusive*.js
jquery.validate*.js

Hope it will help you.希望它会帮助你。

Simply style your input button to look like a link with the following CSS:只需将输入按钮的样式设置为具有以下 CSS 的链接:

 input[type=submit] { background:none!important; border:none; padding:0!important; color:#069; text-decoration:underline; cursor:pointer; }
 <input type="submit" value="Give me Free Advice" />

This will allow all the built in validation to work as is, with no difference to the user other than the appearance.这将允许所有内置验证按原样工作,除了外观之外对用户没有任何区别。

If your requirement is to use ajax to post you must manually call the validate method within the JavaScript with jquery unobtrusive.如果您的要求是使用 ajax 发布,您必须使用不显眼的 jquery 手动调用 JavaScript 中的 validate 方法。

This can be done with the following:这可以通过以下方式完成:

    // replace the `formId` with the one defined in your view
    var $form = $('#formId');
    $.validator.unobtrusive.parse($form);
    $form.validate();
    if ($form.valid()) {
      // Do post
   }

In order to manually pull out the error messages you can use this:为了手动提取错误消息,您可以使用:

$.each($form.validate().errorList, function (key, value) {
            $errorSpan = $("span[data-valmsg-for='" + value.element.id + "']");
            $errorSpan.html("<span style='color:red'>" + value.message + "</span>");
            $errorSpan.show();
        });

Which replaces the ValidationMessageFor markup with the failure messages.它用失败消息替换了ValidationMessageFor标记。

I would force the validation in your click handler, as jQuery seems to do that only for the automatic submit of the form (and not for the manual post() you are doing):我会在您的click处理程序中强制验证,因为 jQuery 似乎只为表单的自动提交(而不是您正在执行的手动post()执行此操作:

$('.btn').click(function (e) {
   if ($('#YourFormIdHere').valid()) { // Will force validation
      $.post(...);
   }
});

As your making an Ajax request to the Action , your validations will not be reflected as the view is not rendered again .当您向Action发出Ajax请求时,您的验证将不会被反映,因为视图不会再次呈现 To stay on the same track you can return the JSON like要保持原样,您可以像这样返回 JSON

return Json(new {Valid = validState,
                Errors = Get Errors FromModel State, 
            });

and then repopulate using the JavaScript.然后使用 JavaScript 重新填充。

Another Way could be around making custom Helpers which will |make a POST request to the desired Action.Code Reference for the same is here .另一种方法可能是制作自定义帮助程序,它会向所需的 Action.Code 发出 POST 请求, 这里是相同的。

And at last what you can do is create a HTML button and make a POST request.最后,您可以做的是创建一个 HTML 按钮并发出 POST 请求。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM