下面是一个非常简单的MVC三元组,用于尝试解决问题。
除了我将状态代码更改为500并且点击提交按钮为Error/StatusCode
而不是Error/StatusCode/500
之后我得到的网址似乎有效。我该怎么改变它?
我很欣赏这是一个简单的问题,但我找不到正确的关键词来谷歌答案。
模型
public class ErrorModel
{
[DisplayName("Status Code")]
public string StatusCode { get; set; }
public ErrorModel(string statusCode)
{
HttpStatusCode code;
if (! Enum.TryParse(statusCode, out code))
{
code = HttpStatusCode.NotFound;
}
StatusCode = ((int)code).ToString();
}
public ErrorModel(HttpStatusCode statusCode = HttpStatusCode.OK)
{
StatusCode = ((int)statusCode).ToString();
}
}
查看
@using WebApplication1.Models
@model WebApplication1.Models.ExcelModel
@using (Html.BeginForm("StatusCode", "Error", FormMethod.Post))
{
<p>
<div class="editor-label">
@Html.LabelFor(model => model.StatusCode)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.StatusCode, null, "id")
</div>
<input type="submit" value="Submit" />
</p>
}
控制器
public class ErrorController : Controller
{
static readonly List<HttpStatusCode> ErrorCodes = new List<HttpStatusCode>(){
HttpStatusCode.Unauthorized, HttpStatusCode.Forbidden, HttpStatusCode.NotFound, HttpStatusCode.InternalServerError};
public ActionResult StatusCode(string id)
{
ViewBag.Message = "";
if ((id == null) || (ErrorController.AreEqual(HttpStatusCode.OK, id)))
{
return View("StatusCode", new ErrorModel(HttpStatusCode.OK));
}
foreach (HttpStatusCode errorCode in ErrorCodes)
{
if (ErrorController.AreEqual(errorCode, id))
{
return View("HttpError", new ErrorModel(errorCode));
}
}
ViewBag.Message = "Exception " + id
+ @" is not supported, see https://msdn.microsoft.com/en-us/library/system.net.httpstatuscode(v=vs.110).aspx for further details";
return View("HttpError", new ErrorModel(HttpStatusCode.InternalServerError));
}
static private bool AreEqual(HttpStatusCode httpCode, string statusCode)
{
return (statusCode == ((int)httpCode).ToString());
}
}
答案 0 :(得分:1)
您正在使用POST
method提交表单。这不会包含url中的表单元素值,但会包含在请求正文中。
如果您希望表单字段值成为URL的一部分,请将表单方法更改为GET
。使用GET
时,如果发布了表单,则发送到服务器的数据将作为查询字符串值附加到URL。
@using (Html.BeginForm("StatusCode", "Error", FormMethod.Get))
{
<div class="editor-label">
@Html.LabelFor(model => model.StatusCode)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.StatusCode, null, "id")
</div>
<input type="submit" value="Submit" />
}
现在,当用户提交表单时,浏览器会向Error/StatusCode
网址发出GET请求,并将表单数据附加到网址。
/Home/StatusCode?id=500
答案 1 :(得分:1)
动态更改操作的url可能是一个解决方案,下面的代码显示了一种最简单的方法。
<script>
$(document).ready(function() {
$('form').submit(function(){
this.action = this.action + '/' + $('#StatusCode').val();
})
});
</script>