开发者

Strongly Typed Views Model on a RedirectToAction

开发者 https://www.devze.com 2023-01-27 17:47 出处:网络
I have two action methods that look like this [HttpPost] public Actio开发者_JAVA百科nResult Search(Models.InputModel input)

I have two action methods that look like this

    [HttpPost]
    public Actio开发者_JAVA百科nResult 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);
    }

Is there a standard best practices way to do something like this?


Erx_VB.NExT.Coder is correct. The code in the search action is not needed. I assume you did this, because your form is posting to /[controller]/Search? You can still use the search.aspx view if you like and just point the form to /[controller]/List like below.

<% 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>


I agree you should combine them into a single ActionResult. An alternative way of doing so would be to create a custom route. So in your Global.asax file, add the following to your RegisterRoutes function:

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

That will automatically map any calls to Search to List, and will remove the need for having both ActionMethods defined in your code


Yes, you should just delete the Search action as its just duplicating code (same code as List) and then redirecting to list! So, code there is redundant. If you want, you can rename your combines action to make more meaningful sense to your code now that you've combined them, perhaps SearchToList() or something. Not using redirects when they are not needed is best practice.

Let me know if this answers your question or if i can do anything more for you, thanks.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号