简体   繁体   中英

Asp.net MVC client validation

I am building asp.net mvc5 application and don't have enough knowledge to solve it. I have a form which needs to be validated and then post using ajax. I use 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. If function returns false form is not submited but if returns true form is submitted. I successfully get the data in json format. My fetched data is inside success callback from ajax and can't be used outside it so inside success callback i have validation code. 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

try this because using Dataannotations you can handle both client side and server side validations

so please try ....

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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