使用HttpGet重定向循环MVC3搜索表单

时间:2012-01-12 08:22:16

标签: c# asp.net-mvc-3 routes http-get

希望有人可以提供帮助,因为我昨天晚上的大部分时间都在绞尽脑汁!基本上,我正在尝试使用HttpGet获取搜索表单,因此我可以通过以下URL从外部源检索结果:

http://url.com/Area/Controller/Action/SearchCategory/SearchCriteria

我创建并将模型传递给我的视图,其中包含 SearchCategory SearchCriteria 的两个属性,并在视图中包含相关的HTML控件。如果我同时选择一个类别并输入符合我标准的内容,则此功能非常有效。但是,如果我没有按照我的标准输入任何内容,我会获得无限重定向。我对此特定功能的路线如下所示:

context.MapRoute(
    "Dashboard-Search",
    "Area/Controller/Action/{SearchCategory}/{SearchCriteria}",
    new { 
        controller = "Controller", 
        action = "Action", 
        SearchCategory = "", 
        SearchCriteria = "" 
    }
);

我确实让我的模型实现了IValidateableObject并验证了输入的内容,但显然路由绑定在任何可以验证之前完成。

任何想法???

路线

context.MapRoute(
    "Dashboard-Search-NoCriteria",
    "HEP/Dashboard/Search/{category}",
    new { controller = "Dashboard", action = "Search", category = "Case No" }
);

context.MapRoute(
    "Dashboard-Search",
    "HEP/Dashboard/Search/{category}/{criteria}",
    new { controller = "Dashboard", action = "Search", category = "Case No", criteria = "" }
);

控制器操作

[HttpGet]
public ActionResult Search(string SearchCategory, string SearchCriteria)
{
    // create new instance of model and add search criteria so entered
    // data persists on post back
    DashboardModel model = new DashboardModel() {
        SearchCategory = SearchCategory,
        SearchCriteria = SearchCriteria
    };
    model.Search(SearchCategory, SearchCriteria);

    // return the HTML view of another controller that displays the same list,
    // only this time, the list is filtered according to GET data
    return View("Overview", model);
}

HTML表单

@using (Html.BeginForm("Search", "Dashboard", FormMethod.Get)) {

    @Html.LabelFor(m => m.SearchCategory, "Category:")
    @Html.DropDownListFor(m => m.SearchCategory, new List<SelectListItem>() {
        new SelectListItem() { Selected = true, Text = "Category", Value = "Category" }
    })

    @Html.LabelFor(m => m.SearchCriteria, "Criteria:")
    @Html.TextBoxFor(m => m.SearchCriteria)

    <input type="submit" value="Search" class="button" />

}

3 个答案:

答案 0 :(得分:0)

您的路线现在与您的搜索表单不符。

满足您的Dashboard-Search路线的网址应如下

http://example.com/HEP/Dashboard/Search/SampleCategory/SampleCriteria

您的表单将依次生成对URL的GET请求:

http://example.com/HEP/Dashboard/Search/?Category=SampleCategory&Criteria=SampleCriteria

很可能您的方法Search(string SearchCategory, string SearchCriteria)从未被调用过 - 我建议您将请求重定向回仅显示搜索视图的方法,而不会实际执行任何搜索。

如果您需要更多解释或代码,请显示整个 RegisterRoutes方法。

答案 1 :(得分:0)

[HttpGet]
public ActionResult Search(string SearchCategory = null, string SearchCriteria = null)

这将允许您的控制器在不处理searchcategory或searchcriteria的情况下工作,只要您处理它们为空的情况。

答案 2 :(得分:0)

我建议使用单一路线,然后通过使条件可选来设置默认值。

context.MapRoute(
    "Dashboard-Search",
    "HEP/Dashboard/Search/{category}/{criteria}",
    new { controller = "Dashboard", action = "Search", category = "Case No", criteria = UrlParameter.Optional });