我正在尝试通过 Ajax 传递 html 代码,如下所示:
使用插件“summernote”(所见即所得编辑器)
var description = $('#ticketDescription').code();
这给我举个例子:
<span style="font-weight: bold;">asdasdasd<span>sadasd
当 Ajax 处理时,会出现 500 内部错误
$.ajax({
url: '/Ticket/NewTicket',
type: 'POST',
data: {
companyId: companyId,
subject: subject,
ticketDescription: description
},
success: function(result) {
....
},
error: function(result) {
}
});
通过从字符串中删除“<”字符解决了该问题。 有什么办法解决这个问题吗? 谢谢
编辑:到目前为止我发现的唯一方法是: 在 JavaScript 中:
description = escape(description);
在 Controller 中:
ticketDescription = HttpUtility.UrlDecode(ticketDescription);
正确吗?
最佳答案
ValidateInput 和 AllowHtml 属性是您需要在属性中设置的内容
默认情况下,Asp.Net MVC 不允许用户提交 html,以避免对您的应用程序进行跨站脚本攻击。
验证输入属性
这是允许提交 HTML 的简单方法。此属性可以在 Controller 级别或任何操作方法上启用或禁用输入验证。 在 Controller 级别验证输入
[ValidateInput(false)]
public class HomeController : Controller
{
public ActionResult AddArticle()
{
return View();
}
[HttpPost]
public ActionResult AddArticle(BlogModel blog)
{
if (ModelState.IsValid)
{
}
return View();
}
}
现在,用户可以成功提交此 Controller 的 Html。 在操作方法级别验证输入
public class HomeController : Controller
{
public ActionResult AddArticle()
{
return View();
}
[ValidateInput(false)]
[HttpPost]
public ActionResult AddArticle(BlogModel blog)
{
if (ModelState.IsValid)
{
}
return View();
}
}
现在,用户可以成功提交此操作方法的 Html。
ValidateInput 属性的限制 该属性也存在问题,因为它允许所有属性的 Html 输入,但这是不安全的。由于您只为一两个属性启用了 Html 输入,那么如何执行此操作。要允许单个属性输入 Html,您应该使用AllowHtml 属性。
AllowHtml 属性
这是允许提交特定属性的 HTML 的最佳方式。此属性将添加到模型的属性中,以仅绕过该属性的输入验证。这种显式声明比 ValidateInput 属性更安全。
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;
public class BlogModel
{
[Required]
[Display(Name = "Title")]
public string Title { get; set; }
[AllowHtml]
[Required]
[Display(Name = "Description")]
public string Description{ get; set; }
}
确保您已从 Conroller 或 Action 方法中删除了 ValidateInput 属性。现在,用户只能成功提交 Description 属性的 Html。
关于javascript - 通过 Ajax Asp.Net MVC 传递 HTML 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32633815/