【发布时间】:2015-10-13 15:34:53
【问题描述】:
我已允许在模型属性上使用 HTML,如下所示:
型号
public class FooViewModel
{
[AllowHtml]
public string Description { get; set; }
}
查看
@using (Html.BeginForm("EditDescription", "Foo", FormMethod.Post))
{
@Html.AntiForgeryToken();
<input type="hidden" value="@(Model != null && Model.Item1 != null ? Model.Item1 : string.Empty)" name="fooId" />
<p>
<textarea name="Description" cols="100" id="Description">
@(Model != null && Model.Item2 != null ? Model.Item2 : string.Empty)
</textarea>
</p>
<p><input type="submit" value="Submit" /></p>
}
@section Scripts {
@Scripts.Render("~/bundles/nicEdit")
<script type="text/javascript">
bkLib.onDomLoaded(function()
{
new nicEditor({fullPanel : true}).panelInstance('Description');
});
</script>
}
控制器
public class FooController
{
public ActionResult EditDescription(string fooId)
{
if (Request.HttpMethod == "POST")
{
using (var context = new ApplicationDbContext())
{
var foo = context.Foos
.SingleOrDefault(f => f.Id == fooId);
// I get the HttpRequestValidationException here
foo.Description = Request["Description"];
context.SaveChanges();
return RedirectToAction("MyProfile");
}
}
}
}
仍然,我收到请求验证异常。我什至尝试用 ValidateInput(false) 注释整个操作方法,因为 View 只有一个字段,这是模型上的单个属性,但我仍然不断收到异常。
我清除了 ASP.NET 临时文件和文件夹缓存,清理并重建了我的解决方案,但均无济于事。
【问题讨论】:
-
您的基本代码有很多基本问题。你不应该使用 Request.HttpMethod 而应该使用HttpPost and Httpget。其次,您没有使用绑定来发回模型,因此您的属性几乎没用。
-
@ErikPhilips 我注意到所有这些。我从 MVC 版本 1 开始就一直在使用它。这个特定的操作和它的整个流程是我匆忙完成的,在与客户达成一致后,我们会回到它来修复它,现在是时候了。在您发表评论后,我通过分离每种方法的操作并实际发布回模型来修复它。我只是没有意识到(正如您推断的那样)请求验证与没有为每个 HTTP 请求提供单独的方法之间的相关性。
标签: asp.net asp.net-mvc asp.net-mvc-5.2