开发者

How to store HTML code in ASP.NET MVC2 Model

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开发者_C百科: 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.


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(...) { ... }


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

[ValidateInput(false)]


  • 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"/>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜