您的位置:首页 > Web前端 > HTML

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

2016-11-10 15:41 369 查看
只需设置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. 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: