I have an MVC开发者_如何转开发 appilcation with a model which uses the [Required]
attibute for a field. When the validation for this attribute fails, I would like to show a hyperlink in the error message.
When I add <a href="link">link</a>
, the text of the link is displayed as is in the error message. How can I show a link in the error message which is displayed using the Html.ValidationMesssageFor(model=>model.attibute)
?
I am using the Razor view engine.
Can we add any style to error message in order to show the hyperlink.
Create an extension method like the following somewhere in your solution:
using System.Web;
namespace MvcApplication.Extensions
{
public static class HtmlStringExtensions
{
public static IHtmlString Raw(this IHtmlString htmlString)
{
return new HtmlString(HttpUtility.HtmlDecode(htmlString.ToString()));
}
}
}
Then, in each of your views add the following using statement:
@using MvcApplication.Extensions
Or you could add the following to your web.config
<pages>
<namespaces>
<add namespace="MvcApplication.Extensions" />
</namespaces>
</pages>
Once you've done these two steps, you will be able to get an un-encoded html string, like you are looking for, by changing your ValidationMessageFor() call to:
Html.ValidationMesssageFor(model=>model.attibute).Raw()
The validation text is encoded before the ValidationSumary or ValidationFor, etc...
you just need tu decode the html, then create an MvcHtmlString ...
Exemple :
@HttpUtility.HtmlDecode(Html.ValidationSummary().ToString()).ToMvcHtmlString()
this is an extension i have made to make MvcHtmlString :
namespace System
{
public static class StringExtension
{
public static System.Web.Mvc.MvcHtmlString ToMvcHtmlString(this string value)
{
return System.Web.Mvc.MvcHtmlString.Create(value);
}
}
}
or you can create an HtmlHelper if you plan to reuse this:
namespace System.Web.Mvc.Html
{
public static class FormHelper
{
public static MvcHtmlString ValidationSummaryEx(this HtmlHelper htmlHelper, bool excludePropertyErrors)
{
var original = htmlHelper.ValidationSummary(excludePropertyErrors);
var decoded = HttpUtility.HtmlDecode(original.ToString());
return decoded.ToMvcHtmlString();
}
}
}
Hope it help you or future viewer. Note: it work for all validations Summary and ValidationFor ...
精彩评论