gpt4 book ai didi

c# - asp .net mvc 中带有 View 模型的多个路由参数

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:41:10 25 4
gpt4 key购买 nike

我正在尝试使用路由进行试验,并为搜索生成一个 seo 友好的 url。

目前我有如下 View 模型:

public class SearchFormViewModel
{
//[Required(ErrorMessage="Keyword is required")]
public string Keyword { get; set; }

public IEnumerable<SelectListItem> TransactionTypes { get; set; }
public int TransactionTypeId { get; set; }

public IEnumerable<SelectListItem> RoomLookUps { get; set; }
public int? MinBeds { get; set; }
public int? MaxBeds { get; set; }
...
}

提交此表单后,它会转到 Controller :

    public ActionResult SearchProperties(SearchFormViewModel viewModelInp)
{
// Perform search;
}

并显示搜索结果。但是,生成的 url 如下:

http://localhost:49191/search/searchproperties?Keyword=London&TransactionTypeId=2&MinBeds=&MaxBeds=&MinPrice=&MaxPrice=

我需要一个看起来像这样的 URL

http://localhost:49191/flats-to-rent/London?MinBeds=&MaxBeds=&MinPrice=&MaxPrice=

我不确定如何将参数从 ViewModel 传递到 Route

以下路线不起作用:

routes.MapRouteLowercase(
"Search-Properties-Buy",
"flats-to-rent/{Keyword}",
new { controller = "Search", action = "SearchProperties", Keyword = UrlParameter.Optional },
new { TransactionTypeId = "2" }
);

我尝试了各种其他方法,但似乎都不起作用,我收到 404 错误。

我找不到任何可能对我有帮助的例子。

最佳答案

好吧,我试着给你一个解决方案。放置一个包含由 asp.net mvc 生成的基本路由的输入字段:

<input type="hidden" value="@Url.Action("SearchProperties", new { Keyword = "{Prototype}" })" id="BaseSearchURL" />

如您所见,我指定了一个值为“{Prototype}”的关键字,这指示 asp.net mvc 提供您配置的自定义路由,并且在呈现后,在页面 HTML 中您应该看到类似这样的内容:

<input type="hidden" value="server/flats-to-rent/{Prototype}" id="BaseSearchURL" />

之后,您可以使用 jquery 覆盖提交按钮按下事件,您可以编写自定义代码:

$(document).ready(function() {
$('input[type=submit]').submit(function() {
var baseURL = $('#BaseSearchURL').val();
var keyword = $('input[name=Keyword]');
var action = baseURL.replace('{Prototype}', keyword);
var form = $(this).parents('form');
// Get all parameter except Keyword
var params = $('input[name!=Keyword], select, textarea', form).serialize();
action += "?" + params;
document.location = action;
});
});

步骤很简单:

  • 获取之前生成的路由模板
  • 获取必须替换为“{Prototype}”的关键字;
  • 获取表单参数并将它们附加到操作中
  • 调用 document.location 以启动特定 URL。

关于c# - asp .net mvc 中带有 View 模型的多个路由参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19881971/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com