1

我使用 MVC 2 已经有一段时间了,我完成了 ReturnToAction 和 ValidationSummary - 但这有点不同,因为我的“提交”按钮是由 javascript/JQuery 控制的 - 我调试了动作,它确实进入了正确的控制器动作,但一旦它通过 RedirecToAction,什么都不会发生....

我的第二个问题是我的 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();  
} 

感谢您的帮助-这使我难以忍受

4

2 回答 2

2

它在调试器中通过 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);

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

于 2010-12-26T23:27:09.110 回答
0

我认为你有几个问题。

  • 重定向未按您预期的方式发生

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

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

  • ValidationSummary 未显示。

您的 ValidationSummary 没有显示有两个原因。首先是因为我刚才描述的ajax return 的事情。第二个是您在执行RedirectToAction. 除非您显式处理 ModelState 传输(通常通过将其导出到 TempData 并在目标操作中导入),否则它会在您重定向时丢失。

于 2010-08-16T02:12:18.353 回答