Asp.Net MVC 2 - 奇怪的行为:RedirectToAction 和 ValidationSummary 不起作用

发布于 2024-09-11 03:40:54 字数 5437 浏览 2 评论 0原文

我已经使用 MVC 2 一段时间了,我完成了 ReturnToAction 以及 ValidationSummary - 但这有点不同,因为我的“提交”按钮是由 javascript/JQuery 控制的 - 我调试了操作,它确实进入了正确的位置 ?

我的第二个问题是我的 ValidationSummary 无法显示 - 我运行一个测试,当 ModelState 无效时它返回一个视图时 - 什么也没有显示

这是我的问题吗 按钮/表单/提交/JQuery?

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">      

<script type="text/javascript">  
    $(function () {  

            /*stuff here to setup some JQuery Sortable lists*/  

        $("#UpdateButton").click(function () {  

            //create Arrays from JQuery Sortable List and go to Action for "submit"                   //processing  

            $.ajax({  
                url: '/Admin/SortedLists/',  
                data: { items: editedRoles, items2: $("#deleteList").sortable('toArray') },  
                type: 'POST',  
                traditional: true  
            });  
        });  

            //go to Action and just "Reload" the page  
        $("#UndoButton").click(function () {  
            //reload the page  
                var url = '<%= Url.Action("EditRoles") %>';                
            window.location.href = url;  
        });  

        $("#roleList, #deleteList").disableSelection();  
        $("#deleteList").hide();  
    });  


    function addNewRole() {  
        var text = $("#New_Role").val();  

        $("#roleList").append('<li id="-1~' + text + '" class="ui-state-default">' +  
                              '<span class="ui-icon ui-icon-closethick"></span>' +  
        //                    '<span class="ui-icon ui-icon-arrowthick-2-n-s"></span>' +  
                              '<input id="-1" type="text" value="' + text + '" />' +                                    
                              '</li>');  
        $("#roleList").sortable('refresh');  
    }  
</script>  

<%= Html.ActionLink("Back", "Index") %>      

<% using (Html.BeginForm()) { %>    
    <br />       
    <%= Html.Encode(ViewData["Message"]) %>  
    <%=Html.ValidationSummary(true, "Edit was unsuccessful. Please correct the errors and try again.")%>  
    <div class="demo">         

        <%=Html.TextBox("New Role", "New Role")%>  
        <a href="javascript:addNewRole()"> Add</a>  

        <br />  
        <br />  
        <ul id="roleList" class='droptrue'>  

         //create an unordered list with textboxes and a close icon  
            <%  
           foreach (var item in Model.Roles)  
           {%>                                   
             <li class="ui-state-default" id="<%=Html.AttributeEncode(item.Id)%>~<%=Html.AttributeEncode(item.Name)%>"><span class="ui-icon ui-icon-closethick"></span><%=Html.TextBox(item.Id.ToString(), item.Name, new {@id = item.Id})%></li>                                                                              

         <% } %>        
        </ul>  

        <ul id="deleteList" class='droptrue'>  
        </ul>         

        <br />  

        </div>        

            <input id="UpdateButton" type="submit" name="submitButton" value="Update" /><%= Html.ValidationMessage("UpdateButton", "*") %>                  
            <input id="UndoButton" type="submit" name="submitButton" value="Undo" />              

<% } %>  

控制器看起来像这样:

public AdminController()  
    {  
        var wrapper = new ModelStateWrapper(ModelState);  
        _rolesService = new RolesService(new RolesRepository(), new RolesValidator(wrapper, new DateValidator(wrapper)));  
    }  

    public ActionResult Index()  
    {  
        return View();  
    }  

    public ActionResult EditRoles()  
    {  
        var roles = _rolesService.FetchAllRoles();  
        return View(new AdminEditRolesViewModel(roles));  
    }  

    [HttpPost]  
    public ActionResult SortedLists(List<string> items, List<string> items2)  
    {  
        var roles = _rolesService.BuildRolesFromList(items);  
        var deletedRoles = _rolesService.BuildRolesFromList(items2);  

        //The Services have contain the ModelState, this is where errors happen  
        //ValidationSummary doesnt show anything  
        if (_rolesService.EditRoles(roles) == false)  
        {  
            roles = _rolesService.FetchAllRoles();  
            return View("EditRoles", new AdminEditRolesViewModel(roles));  
        }  

        if (_rolesService.DeleteRoles(deletedRoles) == false)  
        {  

            roles = _rolesService.FetchAllRoles();  
            return View("EditRoles", new AdminEditRolesViewModel(roles));  
        }  

        _rolesService.Save();  

        //This RedirecToAction is passed, but doesnt actually go to my Index()  
        return RedirectToAction("Index");  

    }  

我的服务处理诸如验证之类的事情,我将 ModelState 和 ModelStateDictionary 包装器传递给它并添加错误 - 我是否错误地添加了错误?

public bool DeleteRoles(IEnumerable<Role> deletedRoles)  
{  
    //some work, if fails add error  

    _validator.AddError("UpdateButton",  
        "Role: " + role.Name +  
        " can not be deleted because Employees still use this";

    return _validator.IsValid();  
} 

感谢您的帮助 - 这让我陷入困境

I've been working with MVC 2 for awhile and ive done ReturnToAction as well as ValidationSummary - but this is a little different in that my "submit" buttons are controls by javascript/JQuery - i debug the action and it does go into the correct Controller Action but once it passes over RedirecToAction, nothing happens....

My second problem is that my ValidationSummary fails to show - i run a test and when it returns a View when ModelState is invalid - nothing shows up

Is it a problem with my buttons/forms/submit/JQuery?

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">      

<script type="text/javascript">  
    $(function () {  

            /*stuff here to setup some JQuery Sortable lists*/  

        $("#UpdateButton").click(function () {  

            //create Arrays from JQuery Sortable List and go to Action for "submit"                   //processing  

            $.ajax({  
                url: '/Admin/SortedLists/',  
                data: { items: editedRoles, items2: $("#deleteList").sortable('toArray') },  
                type: 'POST',  
                traditional: true  
            });  
        });  

            //go to Action and just "Reload" the page  
        $("#UndoButton").click(function () {  
            //reload the page  
                var url = '<%= Url.Action("EditRoles") %>';                
            window.location.href = url;  
        });  

        $("#roleList, #deleteList").disableSelection();  
        $("#deleteList").hide();  
    });  


    function addNewRole() {  
        var text = $("#New_Role").val();  

        $("#roleList").append('<li id="-1~' + text + '" class="ui-state-default">' +  
                              '<span class="ui-icon ui-icon-closethick"></span>' +  
        //                    '<span class="ui-icon ui-icon-arrowthick-2-n-s"></span>' +  
                              '<input id="-1" type="text" value="' + text + '" />' +                                    
                              '</li>');  
        $("#roleList").sortable('refresh');  
    }  
</script>  

<%= Html.ActionLink("Back", "Index") %>      

<% using (Html.BeginForm()) { %>    
    <br />       
    <%= Html.Encode(ViewData["Message"]) %>  
    <%=Html.ValidationSummary(true, "Edit was unsuccessful. Please correct the errors and try again.")%>  
    <div class="demo">         

        <%=Html.TextBox("New Role", "New Role")%>  
        <a href="javascript:addNewRole()"> Add</a>  

        <br />  
        <br />  
        <ul id="roleList" class='droptrue'>  

         //create an unordered list with textboxes and a close icon  
            <%  
           foreach (var item in Model.Roles)  
           {%>                                   
             <li class="ui-state-default" id="<%=Html.AttributeEncode(item.Id)%>~<%=Html.AttributeEncode(item.Name)%>"><span class="ui-icon ui-icon-closethick"></span><%=Html.TextBox(item.Id.ToString(), item.Name, new {@id = item.Id})%></li>                                                                              

         <% } %>        
        </ul>  

        <ul id="deleteList" class='droptrue'>  
        </ul>         

        <br />  

        </div>        

            <input id="UpdateButton" type="submit" name="submitButton" value="Update" /><%= Html.ValidationMessage("UpdateButton", "*") %>                  
            <input id="UndoButton" type="submit" name="submitButton" value="Undo" />              

<% } %>  

And the Controller looks like this:

public AdminController()  
    {  
        var wrapper = new ModelStateWrapper(ModelState);  
        _rolesService = new RolesService(new RolesRepository(), new RolesValidator(wrapper, new DateValidator(wrapper)));  
    }  

    public ActionResult Index()  
    {  
        return View();  
    }  

    public ActionResult EditRoles()  
    {  
        var roles = _rolesService.FetchAllRoles();  
        return View(new AdminEditRolesViewModel(roles));  
    }  

    [HttpPost]  
    public ActionResult SortedLists(List<string> items, List<string> items2)  
    {  
        var roles = _rolesService.BuildRolesFromList(items);  
        var deletedRoles = _rolesService.BuildRolesFromList(items2);  

        //The Services have contain the ModelState, this is where errors happen  
        //ValidationSummary doesnt show anything  
        if (_rolesService.EditRoles(roles) == false)  
        {  
            roles = _rolesService.FetchAllRoles();  
            return View("EditRoles", new AdminEditRolesViewModel(roles));  
        }  

        if (_rolesService.DeleteRoles(deletedRoles) == false)  
        {  

            roles = _rolesService.FetchAllRoles();  
            return View("EditRoles", new AdminEditRolesViewModel(roles));  
        }  

        _rolesService.Save();  

        //This RedirecToAction is passed, but doesnt actually go to my Index()  
        return RedirectToAction("Index");  

    }  

My Services handle things like validation, I pass it the ModelState and a ModelStateDictionary wrapper and add errors - am i adding errors incorrectly?

public bool DeleteRoles(IEnumerable<Role> deletedRoles)  
{  
    //some work, if fails add error  

    _validator.AddError("UpdateButton",  
        "Role: " + role.Name +  
        " can not be deleted because Employees still use this";

    return _validator.IsValid();  
} 

Thanks for any help - this is driving me up the wall

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

本王不退位尔等都是臣 2024-09-18 03:41:04

我认为你有几个问题。

  • 重定向没有按照您期望的方式发生,

我认为这是因为您使用 $.ajax() 调用异步发布表单,但没有处理返回值。 RedirectToAction 返回一个 URL 和一个 HTTP 状态代码 302(可能是 301,我忘了),告诉浏览器请求返回的 URL。您的控制器操作正在将 HTTP 重定向返回到异步 javascript 调用,但异步 javascript 调用不处理它。

您需要更改提交的 JavaScript 或使用 .ajaxSuccess()

  • 验证摘要未显示。

您的 ValidationSummary 未显示有两个原因。第一个是因为我刚才描述的 ajax 返回的东西。第二个是当您执行RedirectToAction 时,您“丢失”了 ModelState。除非您显式处理 ModelState 传输(通常通过将其导出到 TempData 并将其导入到目标操作中),否则在重定向时它将丢失。

I think you have a couple of problems.

  • Redirect not happening the way you expect

I'm thinking this is because your posting the form asynchronously with the $.ajax() call, but you're not handling the return values. A RedirectToAction returns a URL and an HTTP status code of 302 (might be 301, I forget), that tells the browser to request the URL returned. Your controller action is returning a HTTP redirect to an async javascript call, which isn't handling it.

You need to either change your submission JavaScript or handle the return value with something like .ajaxSuccess().

  • ValidationSummary not showing.

Your ValidationSummary isn't showing for two reasons. The first is because of the ajax return thing I just described. The second is you "lost" the ModelState when you did the RedirectToAction. Unless you explicitly handle the ModelState transfer (typically by exporting it to TempData and importing it in the target action), it will be lost when you redirect.

很快妥协 2024-09-18 03:41:01

在调试器中传递RedirectToAction()是正常的。在从该方法返回之前,它实际上不会执行重定向。但你的控制器操作正在运行。您只是看不到任何内容,因为您的前端表示层(即网页)没有执行任何操作来处理 ajax 调用设置的回调。为了解决这个问题,您将创建一个回调函数,如下所示:

        $.ajax({  
            url: '/Admin/SortedLists/',  
            data: { items: editedRoles, items2: $("#deleteList").sortable('toArray') },  
            type: 'POST',  
            traditional: true,
            success: function(data) {
                alert(data);
            }
        });

显然,您将使用“数据”做一些更有用的事情,但我们现在只是显示它。

validatorSummary 未显示,因为创建它的方法不是您在 POST 上执行的操作。它被 RedirectToAction“删除”。为了解决这个问题,您将使用类似的方法:

return View("~/Views/Home/Index.aspx", model);

这会将用户直接发送到那里,并保留您的模型状态,包括验证。

It is normal for it to pass over RedirectToAction() in the debugger. It won't actually do the redirect until it returns from the method. But your controller action is running. You're just not seeing anything because your front-end presentation layer which is the web page isn't doing anything to handle the callback that your ajax call sets. To solve that, you'll create a callback function like so:

        $.ajax({  
            url: '/Admin/SortedLists/',  
            data: { items: editedRoles, items2: $("#deleteList").sortable('toArray') },  
            type: 'POST',  
            traditional: true,
            success: function(data) {
                alert(data);
            }
        });

Obviously you'll do something more useful with 'data', but we're just displaying it for now.

The validatorSummary isn't showing because the method that is creating it is not your action upon POST. It is being 'erased' by the RedirectToAction. To solve that you'll use something like this instead:

return View("~/Views/Home/Index.aspx", model);

This will send the user directly there and will preserve your modelstate, including validations.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文