【问题标题】:how to force partial view to render proper url如何强制部分视图呈现正确的 url
【发布时间】:2015-11-23 22:10:10
【问题描述】:

ASP.NET MVC4 搜索 Razor 局部视图定义为

@inherits ViewBase<MvcMusicStore.ViewModels.SearchViewModel>

@using (Html.BeginForm("Browse", "Store" , FormMethod.Get,
    new { @class = "searchform" }))
{

    @Html.TextBoxFor(model => model.Search, new
{
    @class = "searchfield",
    value = "Search..."
})
    <input class="searchbutton" type="submit" value="@("Search...")" />
    <input type="hidden" value="relevance" name="order" />
}

并在site.cshtml中使用:

@Html.Partial("Search", new MvcMusicStore.ViewModels.SearchViewModel())

如果页面地址是http://localhost:52223/Store/Browse/Kuupakkumine,则使用无效操作/Store/Browse/Kuupakkumine 创建搜索表单。 Kuupakkumine 会自动添加到 url 的末尾:

<form action="/Store/Browse/Kuupakkumine" class="searchform" method="get">
 <input class="searchfield" id="Search" name="Search" type="text" value="Search...">    
<input class="searchbutton" type="submit" value="Search...">
</form>

如何解决这个问题,以便正确的 url,/Store/Browse 将出现在浏览器 html 中?

Storecontroller Browse 方法签名是

[OutputCacheAttribute(VaryByParam = "*", Duration = 0, NoStore = true)]
public ActionResult Browse(string category, string order, int? page, bool? descending,
 int? itemsPerPage, string brand, string color, string @class, string type, bool? grid,
    string search, bool? instock, CartLayout? cartLayout, string id)

【问题讨论】:

  • 方法的签名是什么?
  • 我不明白问题,哪个方法签名? Html.BeginForm 在 MVC 内置方法中
  • 控制器方法-public ActionResult Browse( what are the parameters? )
  • @StephenMuecke 我更新了问题并添加了浏览签名使用默认路由,因此 Kuupakkumine 作为 Id 参数传递给浏览,这将返回无效结果。如果从搜索中调用 Browse,则 id 必须为 null。浏览只需要填写搜索参数
  • 假设你使用默认路由,那么Html.BeginForm("Browse", "Store", new { id = "" }, FormMethod.Get, new { @class = "searchform" }))

标签: asp.net-mvc asp.net-mvc-4 razor asp.net-mvc-partialview razor-2


【解决方案1】:

您使用默认路由 (url: "{controller}/{action}/{id}",) 和您的 Browse() 方法包含匹配的 string id 参数,这意味着 id 的值作为路由值添加。 BeginForm() 方法使用这些值来生成表单action 属性。这种行为很有用,因为如果您(比如说)创建一个表单来编辑模型,并且该模型包含属性 int ID,则不需要为 ID 属性包含隐藏输入。

要覆盖默认行为,您需要将路由值显式设置为null

Html.BeginForm("Browse", "Store", new { id = "" }, FormMethod.Get, new { @class = "searchform" }))

【讨论】:

    【解决方案2】:

    这是由路由引起的,可能你有一个匹配 /Store/Browse/Kuupakkumine (/{Controller}/{Action}/{id}) 的默认路由。

    尝试创建一个没有 id 的新 rote,在上面加上一个特定的名称,然后像这样在你的 Partial 中使用。

    routes.MapRoute("Search", "{Controller}/{Action}");
    

    并在您的 Partial 中使用它。

    Html.BeginForm("Search")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-28
      • 2017-11-15
      • 2018-07-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多