Correct way to handle Ajax calls in ASP.Net MVC 3

后端 未结 3 462
眼角桃花
眼角桃花 2021-01-30 18:58

When coding up Ajax calls in ASP.Net MVC we have a lot of options as far as issuing calls, handling them on the server, and dealing with successes and failures on the client. S

3条回答
  •  礼貌的吻别
    2021-01-30 19:31

    Here's how I do things in some recent projects:

    1) I inject the ajax url in the view with a Url.Action call.

    2) Jqgrid uses GETs to fetch grid data, so in the fill grid controller actions I need to use the JsonRequestBehavior.AllowGet switch in the Json method call.

    3) I recently switched to Microsoft's unobtrusive client-side validation, which has a neat ModelState.IsValid method you can run server-side in your controller action to make sure the same exact validation is also running on the server side without code duplication. It took some work meshing it with jquery.maskedinput and so on to mask/unmask data, here's the article on how to get all that to work.

    4) Regarding displaying the error client side, that's a design issue that has to be fleshed out by the stakeholders. Personally, I didn't like the validation next to the textboxes or a validation summary at the top of the page. I prefer the errors to jump out at your face, so I tweaked Microsoft's jquery.validate.unobtrusive.js to show the error in a popup modal dialog. You can see the code in the solution above in the jquery.validate.unobtrusive.MOD.js file (notice that my version is suffixed with ".mod.js") and you can see the error dialog in the Site.Master.

    Example of controller action:

    [HttpPost]
        public ActionResult Index(PersonalInformation model)
        {
            if (ModelState.IsValid)
            {
                // TODO: sell personal information to sleazeballs
    
                TempData["PersonalInformation"] = model;
    
                return RedirectToAction("Success");
            }
    
            // If we got this far, something failed, redisplay form
            Index_Load();
            return View(model);
        }
    

    Hope this helps,

    Robert

提交回复
热议问题