使用FormCollection时,MVC 3 RTM allowHtml不起作用

B Z*_*B Z 4 asp.net-mvc asp.net-mvc-3

MVC 3 RTM.拥有一个具有AllowHtml属性的模型.在我的控制器操作中,如果操作将FormCollection作为参数,则会抛出异常:

 [HttpPost]
 public ActionResult Edit(FormCollection collection, int id)
 {
   var myEntity = _myRepo.Get(id);

   TryUpdateModel(myEntity);

   return DoSave(myEntity);
 }
Run Code Online (Sandbox Code Playgroud)

从客户端检测到潜在危险的Request.Form值

但是,如果我的控制器操作使用对象而不是FormCollection,则它不会抛出异常.

 [HttpPost]
 public ActionResult Edit(MyEntity postedEntity, int id)
 {
   var myEntity = _myRepo.Get(id);

   TryUpdateModel(myEntity);

   return DoSave(myEntity);
 }
Run Code Online (Sandbox Code Playgroud)

我已经设置好了

httpRuntime requestValidationMode ="2.0"

使用FormCollection时为什么会失败?

Dar*_*rov 9

您不能使用AllowHtml与FormCollection.您可以使用该[ValidateInput]属性,但显然这对所有值都禁用了验证:

[HttpPost]
[ValidateInput(false)]
public ActionResult Edit(FormCollection collection, int id)
{
    var myEntity = _myRepo.Get(id);
    TryUpdateModel(objective);
    return DoSave(objective);
}
Run Code Online (Sandbox Code Playgroud)

据说我会使用以下内容:

[HttpPost]
public ActionResult Edit(MyEntity entity)
{
    if (ModelState.IsValid)
    {
        _myRepo.Save(entity);
        return RedirectToAction("Success");
    }
    return View(entity);
}
Run Code Online (Sandbox Code Playgroud)

  • 绑定`FormCollection`时它不起作用的简单原因是因为没有任何东西可以将你在某些类的某些属性上定义的`AllowHtml`与当前正在执行的请求相关联. (3认同)