gpt4 book ai didi

c# - ASP.NET MVC 删除了 Controller QueryString 操作

转载 作者:太空宇宙 更新时间:2023-11-03 16:20:57 25 4
gpt4 key购买 nike

当我使用默认路由时:

routes.MapRoute(
"Default", //
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional } );

应用找到下面的方法:

public ActionResult News(DateTime? FromDate, DateTime? ToDate)
{
IList<Model.MonthGroupNewsEntry> monthGroupNewsEntries = new services.NewsEntryService(new Data.SqlNewsEntryRepository()).GetMonthGroupNewsEntries();
IList<Model.NewsEntry> newsEntries = new Services.NewsEntryService(new Data.SqlNewsEntryRepository()).GetNewsEntriesWithinDateRange(FromDate,
return View(new Models.NewsViewModel(monthGroupNewsEntries, newsEntries));
}

来自:

<%= Html.ActionLink(b.MonthName + " " + b.Year.ToString() +  " (" + b.EntryCount.ToString() + ")", "News", new { FromDate = b.FromDate, ToDate = b.ToDate}) %>

但是当我尝试使用以下方法从 url 中删除 Controller 时:

routes.MapRoute(
"Default",
"{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional } );

我收到 404 资源未找到错误。

注意:类中的其他方法工作正常,但这些方法没有参数或“id”,它只是用两个 DateTime 调用的方法?当我从 URL 中删除 Controller 时失败的参数。

感谢您提供更新的答案,但是 - 我所做的唯一更改是从上面的“routes.MapRoute”中删除“{controller}/”文本 - 不会出现任何拼写错误等,这也在使用 MVC 3。

进一步:使用 Charx 的建议:

routes.MapRoute(
"SpecificAction",
"{action}/{FromDate}/{ToDate}",
new { controller = "ControllerName", id = UrlParameter.Optional } );

我不再收到 404 错误,但由于日期中的“/”,它给出了“400 - 错误请求”,因此我将日期重新格式化为 dd-MM-YYYY:

<%= Html.ActionLink(b.MonthName + " " + b.Year.ToString() +  " (" + b.EntryCount.ToString() + ")", "News", new { FromDate = b.FromDate.ToString("dd-MM-yyyy"), ToDate = b.ToDate.ToString("dd-MM-yyyy")}) %>

它不再是 404,FromDate 被正确识别,但 ToDate 显示为 null。

Final :我将两个日期的类型更改为字符串并在方法中将它们转换为日期时间 - 现在两个参数都正常 - 我猜它可能是在寻找时间元素第一个参数,因此忽略了第二个参数。

现在唯一突出的事情是需要“id”参数的方法现在似乎将其用作查询字符串 (NewsEnrty?ID=5) 而不是“NewsEntry/5” 如果有人能回答这个问题那么谢谢 - 否则问题已回答- 再次感谢 Chanx。

最佳答案

已编辑。如果您仍然希望能够识别要在您的 URL 中调用的操作,那么您必须指定您的特定操作路由,并确保识别操作所在的正确 Controller :

routes.MapRoute(
"SpecificAction",
"{action}/{FromDate}/{ToDate}",
new { controller = "ControllerName", id = UrlParameter.Optional } );

routes.MapRoute(
"Default", //
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional } );

关于c# - ASP.NET MVC 删除了 Controller QueryString 操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13897453/

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