Part 76 - ValidateInput attribute in mvc 允许文本框输入html标签

只需设置ValidateInput属性为false,即可允许在文本框输入html标签。若需要详细了解,请往下看:

This validateInput attribute is used to enable or disable request validation. By default, request validation is enabled in asp.net mvc,  Let's understand this with an example. 

Step 1: Create an asp.net mvc4 application using Empty template.

Step 2: Add a HomeController. Copy and paste the following code.

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View();
    }

    [HttpPost]
    public <span style="background-color: rgb(255, 255, 153);">string</span> Index(string comments)
    {
        return "Your Comments: " + comments;
    }
}


Step 3: Add Index.cshtml view. Copy and paste the following code.
<div style="font-family:Arial">
@using (Html.BeginForm())
{
    <b>Comments:</b> 
    <br />
    @Html.TextArea("comments")
    <br />
    <br />
    <input type="submit" value="Submit" />
}
</div>

Step 4: Navigate to /Home/Index. Type the following text in the "Comments" textbox and click "Submit".
<h1>Hello</h1>

Notice that, you get an error - A potentially dangerous Request.Form value was detected from the client (comments="<h1>Hello</h1>"). This is because, by default, request validation is turned on in asp.net mvc and does not allow you to submit any HTML, to prevent XSS (Cross site scripting attacks). We discussed XSS in Part 55 & Part 56 of asp.net mvc tutorial.

However, in some cases, you want the user to be able to submit HTML tags like <b>,<u> etc. For this to happen, we need to turn off request validation, by decorating the action method with ValidateInput attribute as shown below.
[HttpPost]
<span style="background-color: rgb(255, 255, 0);">[ValidateInput(false)]</span>
public string Index(string comments)
{
    return "Your Comments: " + comments;
}


At this point, you should be able to submit comments, with HTML tags in it.  

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值