需要允许操作方法字符串参数绑定标记

Bri*_*all 3 asp.net-mvc-3

我有一个操作方法,它接受一个字符串作为其唯一参数。操作方法对其进行转换,并将结果返回给客户端(这是通过 ajax 调用完成的)。我需要允许在字符串值中进行标记。过去,我通过使用 装饰模型上的属性来完成此操作[AllowHtml],但该属性不能在参数上使用,并且该类AllowHtmlAttribute是密封的,因此我无法从它继承。我目前有一项工作,我创建了一个仅具有一个属性的模型,并用上述属性对其进行了装饰,并且这是有效的。

我认为我不应该跳过这个圈子。我是否遗漏了什么,或者我应该向 MVC 团队请求允许在方法参数上使用此属性?

Ale*_*lex 5

如果您需要允许特定参数(与“模型属性”相对)的 html 输入,则没有内置方法可以做到这一点,因为[AllowHtml]仅适用于模型。但是您可以使用自定义模型绑定器轻松实现此目的:

public ActionResult AddBlogPost(int id, [ModelBinder(typeof(AllowHtmlBinder))] string html)
{
    //...
}
Run Code Online (Sandbox Code Playgroud)

AllowHtmlBinder代码:

public class AllowHtmlBinder : IModelBinder
{
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var request = controllerContext.HttpContext.Request;
        var name = bindingContext.ModelName;
        return request.Unvalidated[name]; //magic happens here
    }
}
Run Code Online (Sandbox Code Playgroud)

在我的博客文章中找到完整的源代码和解释: https: //www.jitbit.com/alexblog/273-aspnet-mvc-allowing-html-for-prefer-action-parameters/