我在頁面上進行搜索時有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
這有什麼錯我的路由?如何解決這個問題?
將'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只是隱藏了輸入,所以有一個窗體只是無稽之談) –