MVC ASP.NET MVC3中的AllowHtml属性无效?

8
问题很简单:
假设你有一个叫做Person的模型。
public class Person
{

       public int PersonID {get; set;}

       public string Name {get; set;}

       [AllowHtml] // Allow html in Intro property
       public string Intro {get; set;}

       [ScaffoldColumn(false)]
       public string ComplicatedValue {get; set;}

}

在控制器的创建操作中
[HttpPost]
public ActionResult Create(Person o, FormCollection collection)
{

// whatever code here;

}

如果您运行它,
  1. 输入Intro的纯文本,不会出现任何问题。
  2. 输入Intro的HTML内容,无论如何设置配置文件,都会显示“潜在危险......”

我找到了这个问题的原因。

如果您将函数更改为

public ActionResult Create(Person o) // Get rid of the *FormCollection collection*
{

// whatever code here;

}

这将消除“潜在危险”的错误。
但我的问题是,对于我的应用程序,我必须使用Create Action方法中的第二个参数FormCollection collection,因为我需要使用其他控件值和服务器变量来分配计算值给ComplicatedValue属性。
如果任何ASP.NET MVC3的专家遇到了与我相同的问题,并找到了解决方案,请友好地告诉我。
3个回答

8

这个链接上的论坛详细讨论了这个问题并提供了一些解决方法。

http://forums.asp.net/p/1621677/4161637.aspx

这里是那个帖子中的一个解决方案,可能适用于您:

public ActionResult Create(Person o) // Get rid of the *FormCollection collection*
{    
FormCollection form = new FormCollection(Request.Unvalidated().Form);
// whatever code here;
}

或者我的个人建议:

public ActionResult Create(Person o, int otherControlValue1, int otherControlValue2, ...)
{        
      o.ComplicatedValue = CalculateComplicatedValue(otherControlValue1, otherControlValue2, ...);
      // whatever code here.

}

在我的情况下,我没有使用FormCollection,但是我需要在我的[HttpPost]方法中有一个不同的足迹,因此它存在。我进行了这个hack,并添加了一个虚假的参数:
public virtual ActionResult Edit(int id)
{
    return View(this.repository.GetById(id));
}
[HttpPost]
public virtual ActionResult Edit(int id, int? bogusID)
{            
    var d = repository.GetById(id);
    if (TryUpdateModel(d))
    {
        repository.Save();
        return RedirectToAction("Index");
    }
    return View();
}

这个答案帮助我们解决了问题。非常感谢! - Hüseyin Cevizci
顶部的示例对我有用,除了我必须从Request.Unvalidated().Form中删除额外的()以只保留Request.Unvalidated.Form - Soturi
不要使用虚假的参数,而是使用不同的函数名称(例如Update(int id)),并标记为属性ActionName("Edit")。 - Ted

2
我能否建议使用自定义模型绑定器来替代从FormCollection中获取复杂数据。Scott Hanselman在他的博客文章blog中介绍了创建自定义模型绑定器的方法,可以作为很好的模板。在他的文章中,他编写了一个DateTimeModelBinder,允许通过单个包含日期的输入或一对包含日期和时间的输入来设置DateTime属性。

0

你尝试过了吗

[Bind(Exclude="ComplicatedValue")]

:

[HttpPost]
public ActionResult Create([Bind(Exclude="ComplicatedValue")]Person o)
{
}

?

通过这种方式,您可以在表单上排除设置ComplicatedValue属性,仍然将对象提交为Person类。

希望这有所帮助。


实际上,这会排除 o.ComplicatedValue 属性,但它仍然存在于 FormCollection 中,因此错误仍将被触发。 - InspiredBy

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接