在MVC2中路由。不显示属性

时间:2013-01-07 17:52:15

标签: c# asp.net-mvc asp.net-mvc-2 asp.net-mvc-routing

好时光!在输入URL浏览器中显示路径时出现问题。到网站上的搜索页面。搜索本身工作正常 - 传递“密钥”,显示找到的列表。控制器中的搜索方法采用要搜索的字符串类型的参数:

public ActionResult SearchAllByKey(string key)
        {
            //logic
            return View(<list_of_found>);
        }  

在Global.asax规定的路线中:

routes.MapRoute(
                  "Search",
                  "Search/{key}", 
                  new { controller = "controller_name", action = "SearchAllByKey", key = UrlParameter.Optional } 
              );

从View:

发送Edit to method的方法的表单
<% using (Html.BeginForm("SearchAllByKey", "controller_name", FormMethod.Post, new { enctype = "multipart/form-data" }))
                           {%>
                        <%: Html.ValidationSummary(true) %>
                        <input type="text" id="keyValue" name="key" />
                        <input type="submit" value="Go!" />
                        <% } %>

点击“开始!”时。到搜索结果页面,但URL(输入行浏览器)显示:

http://localhost:PORT/Search

而不是:

http://localhost:PORT/Search/SOME_KEY

如何确保在URL-e中显示“key”?提前致谢

1 个答案:

答案 0 :(得分:1)

您正在发布数据。

使用FormMethod.Get更改您的表单,并确保您的操作仅接受获取(但这是默认设置)

    [HttpGet]
    public ActionResult SearchAllByKey(string key)
    {
        //logic
        return View(new List<string>());
    }  

<强>更新

要实现您的目标,您必须在默认值之前配置您的符号:

routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

routes.MapRoute(
          "Search",
          "{controller}/SearchAllByKey/{key}",
          new { controller = "Home", action = "SearchAllByKey", key = UrlParameter.Optional }
      );

routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);

FORM 应如下所示:

<% using (Html.BeginForm("Search", "Home", FormMethod.Post))
{%>
    <% Html.ValidationSummary(true); %>
    <input type="text" id="key" name="key" value="" />
    <input type="submit" value="Go!" />
<% } %>

你需要改变你的 ActionResult

[HttpGet]
public ActionResult SearchAllByKey(string key)
{
    //logic
    return View(new List<string>());
}

[HttpPost]
public ActionResult Search(FormCollection form)
{
    return RedirectToAction("SearchAllByKey",  new { key = form["key"] });
}

基本上,您的 FORM 会向动作Search发帖,重定向到SearchAllByKey