重新加载页面但由于在 MVC 中路由时 url 错误而出现 404 错误
Reload page but get a 404 error because of wrong url when routing in MVC
我的视图名为 Survey.cshtml
。我目前的 url 是 http://localhost:17471/Campaign/Survey/6184
.
在这个页面中,我有一个 select 语言的下拉菜单。有英语和西班牙语。一是我 select 的语言,我想重新加载页面,因为某些上下文以不同的语言显示。我还是想保持原样 url.
我的代码在Survey.cshtml
.
$("#id").change(function () {
var selectedValue = $(this).find('option:selected').text();
window.location.href = "@Url.Action("Survey1", "Campaign", new {id=Model.SurveyModel.CampaignId, languageName = "languageToken" })".replace("languageToken", selectedValue);
});
但是它会转到 url http://localhost:17471/Campaign/Survey1/6184?languageName=Spanish
我的控制器 CampaignController.cs
有方法。
public ActionResult Survey(int id)
{
// omitted code
return View(model);
}
[HttpPost]
public ActionResult Survey1(int id, string languageName)
{
// omitted here
var view = "Survey";
return View(view,model);
}
我在 RouteConfig.cs 中没有上述方法的路由。我对 MVC 路由不是很了解。有时我会混淆旧的和好的 HTTP URL 编码与 http://site-address/page.html?param1=value1¶m2=value2
和使用 http://site-address/page/value1/value2
.
形式的 MVC 路由
所以帮助我。
您的 Survey1
操作装饰有 [HttpPost]
,这意味着您必须使用客户端的 POST 方法。但是当您使用 window.location.href
进行重定向时,它总是使用 GET 方法。您有两个选择:
- 更改您的控制器操作并删除
[HttpPost]
。
- 使用 POST 方法和其中的值创建一个表单,并使用 javascript 触发该表单上的
submit
事件,而不是使用 window.location.href
。
我的视图名为 Survey.cshtml
。我目前的 url 是 http://localhost:17471/Campaign/Survey/6184
.
在这个页面中,我有一个 select 语言的下拉菜单。有英语和西班牙语。一是我 select 的语言,我想重新加载页面,因为某些上下文以不同的语言显示。我还是想保持原样 url.
我的代码在Survey.cshtml
.
$("#id").change(function () {
var selectedValue = $(this).find('option:selected').text();
window.location.href = "@Url.Action("Survey1", "Campaign", new {id=Model.SurveyModel.CampaignId, languageName = "languageToken" })".replace("languageToken", selectedValue);
});
但是它会转到 url http://localhost:17471/Campaign/Survey1/6184?languageName=Spanish
我的控制器 CampaignController.cs
有方法。
public ActionResult Survey(int id)
{
// omitted code
return View(model);
}
[HttpPost]
public ActionResult Survey1(int id, string languageName)
{
// omitted here
var view = "Survey";
return View(view,model);
}
我在 RouteConfig.cs 中没有上述方法的路由。我对 MVC 路由不是很了解。有时我会混淆旧的和好的 HTTP URL 编码与 http://site-address/page.html?param1=value1¶m2=value2
和使用 http://site-address/page/value1/value2
.
所以帮助我。
您的 Survey1
操作装饰有 [HttpPost]
,这意味着您必须使用客户端的 POST 方法。但是当您使用 window.location.href
进行重定向时,它总是使用 GET 方法。您有两个选择:
- 更改您的控制器操作并删除
[HttpPost]
。 - 使用 POST 方法和其中的值创建一个表单,并使用 javascript 触发该表单上的
submit
事件,而不是使用window.location.href
。