使用的FormCollection当MVC 3 RTM allowHtml不起作用 [英] MVC 3 RTM allowHtml doesn't work when using FormCollection

查看:183
本文介绍了使用的FormCollection当MVC 3 RTM allowHtml不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

MVC 3 RTM。有一个与AllowHtml属性的模型。在我的控制器动作,如果行动的FormCollection作为参数,它会抛出异常:

  [HttpPost]
 公众的ActionResult编辑(的FormCollection收集,INT ID)
 {
   变种myEntity所= _myRepo.Get(ID);   TryUpdateModel(myEntity所);   返回DoSave就会(myEntity所);
 }


  

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


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

  [HttpPost]
 公众的ActionResult编辑(myEntity所postedEntity,INT ID)
 {
   变种myEntity所= _myRepo.Get(ID);   TryUpdateModel(myEntity所);   返回DoSave就会(myEntity所);
 }

我已经安装


  

的httpRuntime
  requestValidationMode =2.0


为什么使用的FormCollection当它失败?


解决方案

您不能使用 AllowHtml 的FormCollection 。你可以使用<$c$c>[ValidateInput]属性但显然对于所有的值该禁用验证:

  [HttpPost]
[ValidateInput(假)]
公众的ActionResult编辑(的FormCollection收集,INT ID)
{
    变种myEntity所= _myRepo.Get(ID);
    TryUpdateModel(目标);
    返回DoSave就会(目标);
}

这是说我会用以下内容:

  [HttpPost]
公众的ActionResult编辑(myEntity所实体)
{
    如果(ModelState.IsValid)
    {
        _myRepo.Save(实体);
        返回RedirectToAction(成功);
    }
    返回视图(实体);
}

MVC 3 RTM. Have a model that has an attribute with AllowHtml. In my controller action, if the action has FormCollection as parameter, it throws the exception:

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

   TryUpdateModel(myEntity);

   return DoSave(myEntity);
 }

A potentially dangerous Request.Form value was detected from the client

However if my controller action uses an object instead of FormCollection it doesn't throw the exception.

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

   TryUpdateModel(myEntity);

   return DoSave(myEntity);
 }

I've already setup

httpRuntime requestValidationMode="2.0"

Why does it fail when using FormCollection?

解决方案

You can't use AllowHtml with FormCollection. You could use the [ValidateInput] attribute but obviously this disabled validation for all values:

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

This being said I would use the following:

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

这篇关于使用的FormCollection当MVC 3 RTM allowHtml不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆