Asp.net mvc 重定向操作上的强类型视图模型

Asp.net mvc 重定向操作上的强类型视图模型,asp.net-mvc,redirecttoaction,Asp.net Mvc,Redirecttoaction,我有两个动作方法,看起来像这样 [HttpPost] public ActionResult Search(Models.InputModel input) { if (!IsSearchCriteriaValid(input)) return RedirectToAction("Index"); TempData[TempDataSearchInput] = input; return Redi

我有两个动作方法,看起来像这样

    [HttpPost]
    public ActionResult Search(Models.InputModel input)
    {
        if (!IsSearchCriteriaValid(input))
            return RedirectToAction("Index");

        TempData[TempDataSearchInput] = input;

        return RedirectToAction("List");
    }

    public ActionResult List()
    {
        var input  = TempData[TempDataSearchInput] as Models.InputModel;

        if (!IsSearchCriteriaValid(input))
            return RedirectToAction("Index");

        var result = new List<MyDTO>();

        AutoMapper.Mapper.Map( _repository.GetBy(input), results);

        var model = new Models.DisplayListModel { Result = result };
        return View("List", model);
    }
[HttpPost]
公共操作结果搜索(Models.InputModel输入)
{
如果(!IsSearchCriteriaValid(输入))
返回操作(“索引”);
TempData[TempDataSearchInput]=输入;
返回重定向到操作(“列表”);
}
公共行动结果列表()
{
var input=TempData[TempDataSearchInput]as Models.InputModel;
如果(!IsSearchCriteriaValid(输入))
返回操作(“索引”);
var result=新列表();
AutoMapper.Mapper.Map(_repository.GetBy(输入),结果);
var model=new Models.DisplayListModel{Result=Result};
返回视图(“列表”,模型);
}

有没有标准的最佳实践方法来执行类似操作?

是的,您应该删除搜索操作,因为它只是复制代码(与列表相同的代码),然后重定向到列表!所以,代码是多余的。如果需要,可以重命名combines操作,以便在组合它们之后对代码更有意义,可能是SearchToList()或其他。不需要重定向时不使用重定向是最佳做法


请告诉我这是否回答了您的问题,或者我是否可以为您做更多的事情,谢谢。

Erx\u VB.NExT.Coder是正确的。不需要搜索操作中的代码。我想您这样做是因为您的表单正在发布到/[controller]/Search?如果愿意,您仍然可以使用search.aspx视图,只需将表单指向如下所示的/[controller]/列表即可

<% using (Html.BeginForm("foo", "bar", FormMethod.Post, new { id = "myID" }))
       { %>
    <%} %>
 will result in the following HTML:

<form action="/bar/foo" id="myID" method="post"></form>

将生成以下HTML:

我同意您应该将它们合并为一个ActionResult。另一种方法是创建自定义管线。因此,在Global.asax文件中,将以下内容添加到RegisterRoutes函数中:

routes.MapRoute( "MySearch", "MyController/Search",
    new { controller = "MyController", action = "List" }
);

这将自动将任何搜索调用映射到列表,并且将不再需要在代码中定义这两种操作方法

可能重复被投票的ya,因为你是一个新来者:)(并且说我是正确的,lol j/k)试图回馈给那些多次勾引我的家伙。。)哈谢谢^^多年来一直潜伏着,现在是时候尝试回馈了~