ASP.NET MVC5自定义json模型绑定器与HTML内容

时间:2014-05-01 23:27:59

标签: asp.net json asp.net-mvc-5 custom-model-binder

我使用了FromJsonAttribute(由Steve Sanderson创建),它非常棒,但遗憾的是它没有注意AllowHtml属性。我有以下型号:

public class HKNewsPaperViewModel
{
    public int Id { get; set; }

    public string UserId { get; set; }

    public string UserName { get; set; }

    public string RPublisher { get; set; }

    public string REditor { get; set; }

    public string Title { get; set; }

    public bool IsDraft { get; set; }

    public bool IsNew { get; set; }

    public List<HKNewsItemViewModel> NewsItems { get; set; }

    public HKNewsPaperViewModel()
    {
        NewsItems = new List<HKNewsItemViewModel>();
    }

}
public class HKNewsItemViewModel
{
    public int Id { get; set; }

    public string Title { get; set; }

    public string Link { get; set; }

    [AllowHtml]
    public string Body { get; set; }
}

在我的控制器中,我以这种方式接收数据:

    [HttpPost]
    public ActionResult New([FromJson] HKNewsPaperViewModel model)
    {
        return View();
    }

FromJson属性如下所示:

public class FromJsonAttribute : CustomModelBinderAttribute
{
    private readonly static JavaScriptSerializer serializer = new JavaScriptSerializer();

    public override IModelBinder GetBinder()
    {
        return new JsonModelBinder();
    }

    private class JsonModelBinder : IModelBinder
    {
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            var stringified = controllerContext.HttpContext.Request[bindingContext.ModelName];
            if (string.IsNullOrEmpty(stringified))
                return null;
            return serializer.Deserialize(stringified, bindingContext.ModelType);
        }
    }
}

我的问题是我无法传递允许使用AllowHtml属性的html内容。非常感谢!

0 个答案:

没有答案