asp.net mvc路由使用表单获取与2动作和相同的看法
我在页面上进行搜索时有url问题。所以,我有一年文本框,并使用GET方法asp.net mvc路由使用表单获取与2动作和相同的看法
Index.cshtml
@using (Html.BeginForm("Search", "Service", new { Year = Model.Year }, FormMethod.Get))
{
<p>
<div class="form-inline">
@Html.EditorFor(model => model.Year, new { htmlAttributes = new { @class = "form-control", @placeholder = "Enter Year" } })
<button type="submit" class="btn btn-primary"><span class="glyphicon glyphicon-search"></span> Search</button>
</div>
</p>
}
我把BeginForm
搜索作为actionName
因为当重定向到服务/索引服务的表单中搜索按钮索引视图数据不应该在第一次加载。所以,我正在使用另一个Action,“Search”来处理这个请求,如果用户没有输入年份,那么它会加载所有的数据,但是如果用户输入年份,它会根据年。
这里是处理该请求
ServiceController.cs
public ActionResult Index()
{
var vm = new ServiceIndexViewModel();
return View(vm);
}
public async Task<ActionResult> Search(int? year)
{
var vm = new ServiceIndexViewModel();
if (ModelState.IsValid)
{
var list = await service.Search(year);
vm.Services = AutoMapper.Mapper.Map<IEnumerable<ServiceListViewModel>>(list);
}
return View("Index", vm);
}
在控制器和自定义路由处理的路由
RouteConfig.cs
routes.MapRoute(
"ServiceSearch",
"Service/Search/{Year}",
new { controller = "Service", action = "Search", Year = UrlParameter.Optional }
);
// default route
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Company", action = "Index", id = UrlParameter.Optional }
);
但我有网址是这样的:
http://localhost:18132/Service/Search?Year=或http://localhost:18132/Service/Search?Year=2017
,我要显示像URL这
http://localhost:18132/Service/Search或http://localhost:18132/Service/Search/Year/2017
这有什么错我的路由?如何解决这个问题?
首先你的路线应该定义是这样的:
routes.MapRoute(
"ServiceSearch",
"Service/Search/Year/{Year}",
new { controller = "Service", action = "Search", Year = UrlParameter.Optional });
但你的问题是别的东西你的代码没有下降到这个定义的路由,并下降到缺省路由。确保默认路线在这条路线下方,如果它仍然没有在这里评论我,我会告诉你我脑海里有什么。
我已经替换了路由,这里的结果是http:// localhost:18132/Service/Search/Year?Year =如果我没有键入任何Year和http:// localhost:18132/Service/Search/Year ?年份= 2017,如果我输入年份 – Willy
将'new {Year = Model.Year}'添加为路由参数是没有意义的,因为它将绑定输入的值。您将表单提交给GET方法,这意味着输入的值只能作为查询字符串值添加(浏览器不知道有关服务器端路由定义的任何信息,但可以使用javascript构建url并使用'location.href = ..'(并取消表单提交) –
@StephenMuecke是的,你说得对,但我从这个网站得到了代码https://stackoverflow.com/questions/28176634/mvc-asp- net-map-routing-is-not-working-with-form-get-request。它有同样的问题,但为什么他可以做到这一点,我不知道?有什么区别? – Willy
在这个问题中接受的答案没有任何输入 - 它只是发回路由参数的硬编码值(并且OP只是隐藏了输入,所以有一个窗体只是无稽之谈) –