Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC 3 RTM allowHtml doesn't work when using FormCollection

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?

like image 633
B Z Avatar asked Dec 21 '22 17:12

B Z


1 Answers

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);
}
like image 160
Darin Dimitrov Avatar answered Mar 25 '23 03:03

Darin Dimitrov