【问题标题】:send HTML tags in form field on form submit在表单提交时在表单字段中发送 HTML 标签
【发布时间】:2011-04-13 10:36:38
【问题描述】:

我正在尝试向我的控制器操作提交表单,其中一个表单字段包含 HTML 标记,例如 <p> <ul>

我已经添加了

<httpRuntime requestValidationMode="2.0"/>

<pages validateRequest="false" </pages>

在我的web.config,还有

我已经添加了

[ValidateInput(false)] 我的控制器操作

但是当我提交表单时,description 字段包含 HTML 标记,它会给出以下错误:

A potentially dangerous Request.Form value was detected from the client (desc="&lt;ul&gt;&lt;li&gt;Comments: Th...").

我应该/可以做什么,在此先感谢...

我正在使用 VS 2010、MVC、实体框架

编辑

这是视图端代码

 <% using (Html.BeginForm("UpdateProductVariant", "home", new { Id = Model.productVariant.ProductVariantId }, FormMethod.Post))
      {%>
    <table>

            <tr>
                <td>Name:</td>
                <td><%: Html.TextArea("ProductVariantName", Model.product.Name)%></td>
            </tr>

            <tr>
                <td>Description:</td>
                <td><%= Html.TextArea("desc",Model.productVariant.Description)%></td>
            </tr>

控制器端

 [ValidateInput(false)]
        public ActionResult UpdateProductVariant(int id, FormCollection collection, bool pub, bool del, decimal hprice)
        {

【问题讨论】:

  • 它可能与您提到的问题重复,但该问题中提出的解决方案并不能解决我的问题...
  • 尝试使用 Server.HtmlEncode 获取相关值
  • 我错了,您的问题将保持开放。 :)
  • 我相信当前请求上下文中的所有动作都应该有 [ValidateInput(false)] 属性

标签: c# asp.net-mvc entity-framework html-helper form-submit


【解决方案1】:

以下应该有效:

型号:

public class MyViewModel
{
    public string Description { get; set; }
}

控制器:

public class HomeController: Controller
{
    public ActionResult Index()
    {
        var model = new MyViewModel
        {
            Description = "<p>Hello</p>"
        };
        return View(model);
    }

    [ValidateInput(false)]
    [HttpPost]
    public ActionResult UpdateProductVariant(MyViewModel model)
    {
        ...
    }
}

查看:

<% using (Html.BeginForm("UpdateProductVariant", "home", new { Id = Model.productVariant.ProductVariantId }, FormMethod.Post)) { %>
    <%= Html.TextAreaFor(x => x.Description) %>
    <input type="submit" value="OK" />
<% } %>

如果您运行的是 ASP.NET 4.0,您只需将 &lt;httpRuntime requestValidationMode="2.0"/&gt; 添加到您的 web.config。另外你不需要添加&lt;pages validateRequest="false" /&gt;

如果这不起作用,您可能没有使用[ValidateInput(false)] 属性修饰正确的控制器操作。这应该是您将表单发布到的操作。

【讨论】:

  • 添加了控制器端代码,我或多或少与您提出的相同...
  • @3nigma,不完全是。我使用的是强类型视图模型,而您使用的是FormCollection。不确定这是否会改变一些东西,但值得一试。无论如何,使用视图模型是一种很好的做法,它对我有用。
  • 这是你的解决方案中唯一的差异,我的我肯定会尝试它...... tnx
  • 不,如果输入不包含 html 标签,它工作正常... tnx 回复:)
  • @3nigma 我不太确定,但我认为有一个与在 MVC 中使用 FormCollection 相关的错误可能需要补丁 Check This
猜你喜欢
  • 2017-08-31
  • 2012-10-11
  • 2012-08-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-21
相关资源
最近更新 更多