AllowHtml属性不起作用

sup*_*lan 4 c# model-binding asp.net-mvc-3

我有一个具有此属性的模型:

     [AllowHtml]
     [DisplayName("Widget for Table")]
     [StringLength(1000, ErrorMessage = "Maximum chars 1000")]
     [DataType(DataType.Html)]
     public object TableWidget { get; set; }
Run Code Online (Sandbox Code Playgroud)

这是控制器中的create方法:

  //
  // GET: /Admin/Table/Create

  public ActionResult Create(int id)
  {
     Season season = _seasonRepository.GetSeason(id);

     var table = new Table
                     {
                        SeasonId = season.SeasonId
                     };
     return View(table);
  }

  //
  // POST: /Admin/Table/Create

  [HttpPost]
  public ActionResult Create(Table a)
  {
     if (ModelState.IsValid)
     {
        _tableRepository.Add(a);
        _tableRepository.Save();
        return RedirectToAction("Details", "Season", new { id = a.SeasonId });
     }
     return View();
  }
Run Code Online (Sandbox Code Playgroud)

最后这是我的观点:

@model Stridh.Data.Models.Table
@using (Html.BeginForm())
{
   @Html.ValidationSummary(true)
   <fieldset>
      <legend>Fields</legend>
      <div class="editor-label">
         @Html.LabelFor(model => model.Name)
      </div>
      <div class="editor-field">
         @Html.EditorFor(model => model.Name) @Html.ValidationMessageFor(model => model.Name)
      </div>
      <div class="editor-label">
         @Html.LabelFor(model => model.TableURL)
      </div>
      <div class="editor-field">
         @Html.EditorFor(model => model.TableURL) @Html.ValidationMessageFor(model => model.TableURL)
      </div>
      <div class="editor-label">
         @Html.LabelFor(model => model.SortOrder)
      </div>
      <div class="editor-field">
         @Html.EditorFor(model => model.SortOrder) @Html.ValidationMessageFor(model => model.SortOrder)
      </div>
      <div class="editor-label">
         @Html.LabelFor(model => model.TableWidget)
      </div>
      <div class="editor-field">
         @Html.EditorFor(model => model.TableWidget) @Html.ValidationMessageFor(model => model.TableWidget)
      </div>
      <div class="editor-label invisible">
         @Html.LabelFor(model => model.SeasonId)
      </div>
      <div class="editor-field invisible">
         @Html.EditorFor(model => model.SeasonId)
      </div>
      <p>
         <input type="submit" value="Create" />
      </p>
   </fieldset>
} 
Run Code Online (Sandbox Code Playgroud)

当我添加一个没有html的"正常"消息时,所有内容都保存好了,但是在保存时它说有一个潜在危险的Request.Form ......

另一个奇怪的事情是我让[AllowHtml]在另一个模型类中工作.我不知道为什么这会让我烦恼.需要你的帮助.:-)

mar*_*ind 17

你的使用方式AllowHtml应该有效.确保您没有访问HttpRequest.Form代码中任何其他位置的集合(控制器,过滤器等),因为这将触发ASP.NET请求验证和您看到的错误.如果您确实想要访问该变量,那么您应该通过以下代码访问它.

using System.Web.Helpers;

HttpRequestBase request = ..  // the request object
request.Unvalidated().Form;
Run Code Online (Sandbox Code Playgroud)

  • 仅供参考,如果您使用自定义模型绑定,您可以遇到类似问题,您需要使用IUnvalidatedValueProvider来访问值:http://blogs.taiga.nl/martijn/2011/09/29/custom-model-binders -and-请求验证/ (4认同)