简体   繁体   English

ASP.NET MVC客户端验证

[英]Asp.net MVC client validation

I am building asp.net mvc5 application and don't have enough knowledge to solve it. 我正在构建asp.net mvc5应用程序,但没有足够的知识来解决它。 I have a form which needs to be validated and then post using ajax. 我有一个需要验证的表单,然后使用ajax发布。 I use Ajax.BeginForm() 我使用Ajax.BeginForm()

@using (Ajax.BeginForm("ActionMethod", "Controller", new { id =
 "form"}, new AjaxOptions { HttpMethod = "POST", OnBegin =
 "FormValidation", OnSuccess = "WriteMessage" }))

Inside function FormValidation I have my own validation code where, among other things, i have made an ajax call to fetch data from database. 在FormValidation函数内部,我有自己的验证代码,除其他外,我在其中进行了ajax调用以从数据库中获取数据。 If function returns false form is not submited but if returns true form is submitted. 如果函数返回false,则不提交表单,但如果返回true,则提交。 I successfully get the data in json format. 我成功获取了json格式的数据。 My fetched data is inside success callback from ajax and can't be used outside it so inside success callback i have validation code. 我获取的数据在ajax的成功回调内部,因此无法在其外部使用,因此在成功回调内部我具有验证代码。 But when my validation code inside success callback fails i want that form isn't submitted but that error is shown to user. 但是,当我的成功回调中的验证代码失败时,我希望不提交该表单,但向用户显示该错误。 How to stop form from being submitted or perhaps there is another way of doing this. 如何阻止表单提交,或者还有另一种方法。

My controller action: 我的控制器动作:

[HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include="ID,Date,Name,Surname,Adress,ProjectName")] Data data)
        {
            if (ModelState.IsValid)
            {
                db.Data.Add(data);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(data);

        }

why you not use dataannotations ?? 为什么不使用数据注释?

http://www.asp.net/mvc/tutorials/mvc-music-store/mvc-music-store-part-6 http://www.asp.net/mvc/tutorials/mvc-music-store/mvc-music-store-part-6

try this because using Dataannotations you can handle both client side and server side validations 请尝试此操作,因为使用Dataannotations可以同时处理客户端和服务器端验证

so please try .... 所以请尝试....

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

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