Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ModelState.AddModelError encodes HTML

I am noticing a weird issue when using ModelState.AddModelError to validate input on my forms. The output from Html.ValidationMessage is not the true HTML value but it's encoded value and so the CSS style is not applied to the error message.

Example:

private string errorMessage = "<span class=\"negative\">{0}</span><br class=\"hid\" />";
ModelState.AddModelError("title", String.Format(errorMessage, "Tab title is required"));

The output is shown as:

<span class="field-validation-error">&lt;span class=&quot;negative&quot;&gt;URL is Required&lt;/span&gt;&lt;br class=&quot;hid&quot; /&gt;</span>

This didn't use to be the case with their earlier beta's and I am not sure what approach to take here.

Thanks Nick

like image 515
IEnumerator Avatar asked Apr 07 '09 19:04

IEnumerator


People also ask

What does ModelState AddModelError do?

ModelState treats your errors exactly the way it treats errors generated by model binding: When you add an error using AddModelError, the ModelState's IsValid property is automatically set to false. So, after all your additional validation errors, you can just check IsValid to see if you've turned up any new errors.

What is ModelState AddModelError in MVC?

ModelState.AddModelError method accepts two parameters. Key – First parameter, if empty shows error written in the 2nd parameter at place where @Html. ValidationSummary(true, "", new { @class = "text-danger" }) is written in the view.

What is ModelState in asp net?

In short, the ModelState is a collection of name and value pairs that are submitted to the server during a POST. It also contains error messages about each name-value pair, if any are found. ModelState is a property of a Controller instance, and can be accessed from any class that inherits from Microsoft.


2 Answers

There is another way to do it, too, without having to create your own extension.

Say for instance we have the following in one of our controllers:

ModelState.AddModelError("Name", "<b>Please Use a Valid Person Name</b>");

We can then do the following in our view:

@if(Html.ValidationMessageFor(x => x.Name) != null){
    @Html.Raw(Html.ValidationMessageFor(x => x.Name).ToString())
}

The will prevent the error message of '<b>Please Use a Valid Person Name</b>' from being encoded.

like image 72
Roshan Avatar answered Oct 13 '22 14:10

Roshan


Create your own extension method that mimics Html.VallidationMessage...?

I had to do something similar because the built in MVC validation stuff (ModelState, ValidationMessage etc etc) doesn't cater for pages that have more than one form on a page.

like image 44
Charlino Avatar answered Oct 13 '22 12:10

Charlino