How can I maintain ModelState with RedirectToAction?

前端 未结 6 961
日久生厌
日久生厌 2020-12-02 05:57

How can I return the result of a different action or move the user to a different action if there is an error in my ModelState without losing my ModelState information?

6条回答
  •  一整个雨季
    2020-12-02 06:34

    Please don't skewer me for this answer. It is a legitimate suggestion.

    Use AJAX

    The code for managing ModelState is complicated and (probably?) indicative of other problems in your code.

    You can pretty easily roll your own AJAX javascript code. Here is a script I use:

    https://gist.github.com/jesslilly/5f646ef29367ad2b0228e1fa76d6bdcc#file-ajaxform

    (function ($) {
    
        $(function () {
    
            // For forms marked with data-ajax="#container",
            // on submit,
            // post the form data via AJAX
            // and if #container is specified, replace the #container with the response.
            var postAjaxForm = function (event) {
    
                event.preventDefault(); // Prevent the actual submit of the form.
    
                var $this = $(this);
                var containerId = $this.attr("data-ajax");
                var $container = $(containerId);
                var url = $this.attr('action');
    
                console.log("Post ajax form to " + url + " and replace html in " + containerId);
    
                $.ajax({
                    type: "POST",
                    url: url,
                    data: $this.serialize()
                })
                    .done(function (result) {
                        if ($container) {
                            $container.html(result);
                            // re-apply this event since it would have been lost by the form getting recreated above.
                            var $newForm = $container.find("[data-ajax]");
                            $newForm.submit(postAjaxForm);
                            $newForm.trigger("data-ajax-done");
                        }
                    })
                    .fail(function (error) {
                        alert(error);
                    });
            };
            $("[data-ajax]").submit(postAjaxForm);
        });
    
    })(jQuery);
    

提交回复
热议问题