ModelState.AddModelError encodes HTML - asp.net-mvc

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"><span class="negative">URL is Required</span><br class="hid" /></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

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.

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.

Related

Using #Html.ActionLink in a replace function in Razor View

I am returning data from my DB with multiple phrases. One of them being the following text : Submitted an Idea
I want to make the "Idea" in any an all text a hyperlink, so I want to use a replace function in my razor view to replace the word "Idea" with my Html Helper:
#item.RewardType.Replace("Idea", #Html.ActionLink("Idea", "ChallengeIdea", "Ideas", new { id = item.fkiIdeaId }, null))
I've looked around a bit but can not really find anything. Someone suggested using #Url.Action - But the issue remains the same.
How do I do this ? Or is using an Html helper the wrong way of doing this ?
Thanks for any help.
You can try this:
#Html.Raw(item.RewardType.Replace("Idea", $"<a href='/ideas/challengeidea/{item.fkiIdeaId}'>Idea</a>"))
Or
#Html.Raw(item.RewardType.Replace("Idea", "Idea"))
Html helpers are there to help you in general situations. When they produce more complications than value, they have no use
<span>Submitted an Idea</span>
If you have RewardType in a resource and can not use plain html, you could set RewardType to "Submitted an Idea" And use string.format

How to display a name after successful remote validation?

My business web application will have a lot of input controls where the user is expected to enter some kind of code (Country, Zip, Employee ID, etc.).
I'm using RemoteAttribute to validate code entries against my database to ensure that users entered the correct code.
The thing is, my standard feature should be to display a name of entered code if the remote validation is successful or error if the validation is not successful.
I'm not sure how to do this.
The obvious answer is to send Name property along with true value in Json object which jquery unobtrusive validation requires. The cshtml could look something like this:
#Html.LabelFor(m => m.Country)
#Html.EditorFor(m => m.Country, new { data-codename-label="lbnCountry" })
<label ID="lbnCountry"></label>
I'm not sure how to implement such an idea though. Any help is appreciated.
Take a look at this answer which should work for you as well.
Do something on success response for remote validation in mvc
If in that example you choose not to send your value through the custom response header, you can always modify the javascript to do an ajax call to an action/webapi that will return the value in question after a successful validation.

Can't use data attribute that ends in "name"?

I am well aware that you use underscores for data attributes with hyphens ("data_bind" instead of "data-bind", in the object), and they automatically get replaced with hyphens. But I have run into the problem where you can't do this underscore "hack," if the attribute ends with "name". So I have tried both of these, but neither work:
#Html.TextBoxFor(model => model.Street, new { data_encrypted_name = "street" })
#Html.TextBoxFor(model => model.Street, new { #data_encrypted_name = "street" })
When I view the HTML that is generated, for both cases above, it generates:
<input data-encrypted- id="ViewModel_Street" name="ViewModel.Street" type="text" value="" />
At first, I thought this might have something to do with multiple underscores/hyphens, but I tried two more test cases, to see what would happen, and they both worked just fine:
#Html.TextBoxFor(model => model.Street, new { data_encrypted_namme = "street" })
#Html.TextBoxFor(model => model.Street, new { data_name_encrypted = "street" })
So this problem is definitely related to having "name" at the end of the attribute.
Am I doing something wrong or missing something, or is this a bug in how .NET converts the attributes?
(For clarification, we use Braintree Payments, and they require the use of the "data-encrypted-name" attribute on certain inputs, so we can't just choose another attribute name.)
Thanks to Tommy for testing the behavior I described and finding it wasn't a bug for everyone.
After Tommy wrote this, I looked at the Helper we were using. I realized that we were actually using an Extension method called "NameLessTextBoxFor" (which we found here: How to extend html.textboxfor to remove the name attribute?), which removes the name="" attribute from the input before displaying it. I should have confirmed this before posting, but didn't recognize it could affect the HTML attributes passed into it.
And lo and behold, as you would probably expect, the functionality of this method was also cutting off any attribute that contained name="". It was doing a very simple search and replace on that text and removing it. So that was the issue here.
Thanks for your time and attention to this issue and apologize I didn't catch this myself.

symfony validation problem

im testing symfony form validation.
the problem is very simple.
no matter what i put in the body text area and post it, i keep getting "Required" back.
i dont know why.
i just have one validation rule.
here is the code:
code
what is wrong/how can i debug?
thanks
UPDATE: it has something to do with the binding in the controller.
cause even if i delete the validation the form will still not be valid and it will be passed to the template but this time without the "Required".
so it wont be valid no matter if ive got the validation or not.
it has something to do with the embedForm() maybe? someone that has validated an embeded form?
i have printed the error messages out with
<?
foreach ($form->getErrorSchema() as $field => $error) {
printf("%s: %s\n", $field, $error->getMessage());
echo "<br />";
}
?>
and i get:
0: Unexpected extra form field named "body".
thread: body [Required.]
_csrf_token: Required.
Body
do they mean that thread:body is required or csrf is required?
thanks
First of all, try echoing the form without being specific, eg:
<?php echo $form; ?>
If this works, then it's something to do with your form echoing code. I'd suggest checking the HTML source of that page then, to see what the default form code renders, and comparing that with what your code outputs above. If the names of the fields are different, therein lies your answer - it could be a form name format as Radu suggests.
On a separate note, don't forget to use:
<?php echo $form->renderHiddenFields(); ?>
as well in your template, so that the CSRF token field gets rendered. This will remove your "_csrf_token: Required" form error.
Have you checked what parameters are sent through POST?
Maybe adding the following in your form setup method will help:
$this->widgetSchema->setNameFormat('thread[%s]');

Asp.Net MVC - ValidationMessage() - how to prevent HTML escaping?

In my scenario I'd like to display a text with URL link within validation message attached to form element on MVC view. I'm using ValidationExtensions.ValidationMessage extension method, like this:
<%=Html.ValidationMessage(Model.Name) %>
The behavior I'm seeing is that validation message is HTML escaped, what effectively prevents me from adding a link to message. Is there a way to circumvent this behavior? My error messages aren't user-supplied, so I don't think I have to worry about output sanitization here...
I'm guessing that since Html.ValidationMessage is built in you're going to either create your own version, or if you're feeling creative, since it returns a string, assign that and then unescape the characters you want to change back.
string validation = Html.ValidationMessage(Model.Name);
validation = Regex.Replace(validation, ">", "<");
//etc...
You could use the HttpUtility.HtmlDecode(...) method along with your Html.ValidationMessage(...) method to get 'err done :D

Resources