How to store HTML code in ASP.NET MVC2 Model

人走茶凉 提交于 2020-01-06 08:39:49

问题


I have a comment model with string property like this:

[Column]
public string Text { get; set; }

Comment text can have all HTML tags inside (i know it's bad, but i have to). But when i update object, MVC 2 escapes all HTML tags.

Updating method is:

[HttpPost]
public ActionResult Edit(int ID=0)
{
        Comment comment= ID == 0
            ? new Comment ()
            : commentRepository.Comments.First(x => x.ID == ID);

        TryUpdateModel(comment);

        if (ModelState.IsValid)
        {
            commentRepository.Save(comment);
            return RedirectToAction("View/" + comment.ID);
        }
        else
        {
            return View(comment);
        }
    }

How can i update comment text without escaping?

P.S. Also i have problem with column type: when i switch column Text in SQL Server Express from varchar to text, updating model fails:

The data types text and nvarchar are incompatible in the equal to operator.

Exception Details: System.Data.SqlClient.SqlException: The data types text and nvarchar are incompatible in the equal to operator.


回答1:


What you have to do is turn off validation for that particular input field. To do that you can add this filter to you action:

[ValidateInput(false)]

Or if you want to be specific and only turn it off on that one field (maybe it will work on multiple, i haven't tested that though) do something like this:

[ValidateInput(true, Exclude = "YourFieldName")]

This will exclude you field but still check all other fields.

ADDON: Adding filters ca be done in (AFAIK) two way. Here are 2 samples:

[HttpPost, ValidateInput(true, Exclude = "YourFieldName")]
public ActionResult SomeAction(...) { ... }

[HttpPost]
[ValidateInput(true, Exclude = "YourFieldName")]
publiv ActionResult SomeAction(...) { ... }



回答2:


you need to add the below filter on your controller under the [HttpPost] filter;

[ValidateInput(false)]



回答3:


  • Don't use the Text datatype in SQL Server, it's deprecated. Instead use Nvarchar(MAX).
  • To turn off input validation for your action you have to use the ValidateInput attribute on your action method. If you use .net 4 you have to add one more line to your web.config:
<configuration>
  <system.web>
      <httpRuntime requestValidationMode="2.0"/>


来源:https://stackoverflow.com/questions/4324945/how-to-store-html-code-in-asp-net-mvc2-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!