【问题标题】:MVC Partial Views, GET and routingMVC 部分视图、GET 和路由
【发布时间】:2013-10-25 19:44:51
【问题描述】:

美好的一天, 这是我的第一个问题,所以请善待。我刚刚从表单迁移到 mvc。 我做了以下路线(下)。我构建了一个局部视图,其中还包含 2 个其他局部视图(如下所示)。 提交后,网址将类似于 'Find/Index?Region=3&Interest=1'

  1. 创建与定义的路由匹配的友好 url 的最佳方法是什么 '查找/索引/In-Wales-3/Sport-1'?我可以发布然后重定向,但我认为这可能效率低下。更好的方法可能是使用 jquery?

  2. 还请说明使用的设计是否正确或是否可以改进?分离视图的原因是因为它们用于多个视图。

提前致谢!

路由配置

routes.MapRoute(
name: "Find",
url: "{controller}/{action}/In-{region}-{rid}/{interest}-{iid}",
defaults: new { controller = "Find", action = "Index", region = UrlParameter.Optional,
                            rid = UrlParameter.Optional,
                            interest = UrlParameter.Optional,
                            iid = UrlParameter.Optional
            });

在母版页上呈现的部分视图

@model SimpleFriendFinderModel
    <h1>Find</h1>
    <div>
        @using (Html.BeginForm("Index", "Find", FormMethod.Get))
        {
            @Html.Partial("_RegionDropDown", @Model.Regions)
            @Html.Partial("_InterestDropDown", @Model.Interests)
            <div>
                &nbsp;
                <button>SEARCH</button>
            </div>
        }
    </div>

区域局部视图

@model IEnumerable<Region>

<select id="Region" name="Region">
<option>REGION</option>
    @{ foreach(var item in Model) {
        <option value="@item.RegionID">@item.RegionName</option>
    }
}
</select>

另一个局部视图是 Region 的复制品,但显然是不同的模型。

【问题讨论】:

  • 关于你的第一个问题,其实很好。打开页面时,没有帖子,是Find/Index/In-Wales-3/Sport-1格式的网址吗?
  • 嗨,不,这是生成该网址的目的。实际的 url 是 Find/Index?Region=Wales&rid=3&Interest=Sport&iid=1。好丑!!
  • 啊,我用过一次类似的东西。能贴出完整的路线图吗?我知道代码中出现的顺序非常重要。
  • 您好 Stefan,感谢您的意见。我知道路由功能在模式匹配方面是基于 FCFS 工作的。路线设置不是问题。问题是如何将表单提交到该 URL。使用 GET,我不知道我的下拉值是否有占位符函数。或者我可以发布然后执行 RedirectResult 但这可能效率低下。干杯。
  • ..hmm 现在我明白你的意思了......并试图弄清楚:|

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


【解决方案1】:

对于部分视图;如果您在其他页面上重新使用它,这是要走的路。您可以将其视为“封装逻辑”。

更新:如果您只是对下拉列表使用部分视图,请忽略以上内容。有一个 HtmlHelper,Html.DropDownListFor()

对于第一部分;顺序是相关的:

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

routes.MapRoute(
          name: "Pretty",
          url: "{controller}/{action}-{id}/Something",
          defaults: new { controller = "Test", action = "Foo", id = UrlParameter.Optional }
      );

//default route
routes.MapRoute(
          name: "Default",
          url: "{controller}/{action}/{id}",  
          defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional    }
        );

例如,如果您想将 URL 格式化为:

http://local:23802/Test/Foo-5/Something

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-07-27
    • 2012-04-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-27
    • 2021-12-18
    相关资源
    最近更新 更多