I want to show a image instead of text when validation fails but ValidationMessageFor encodes my 'validationMessage'.
I'm trying to specify a validationMessage using a plain img tag declaration
How can i do that?
Thanks
You will need to create your own HTMLHelper.
Something like:
public static MvcHtmlString ValidationImage(this HtmlHelper htmlHelper)
{
if (!htmlHelper.ViewData.ModelState.IsValid)
{
//todo: strip out the information you need from the model and return <img/> tag(s).
}
return null;
}
you can declare a const string containing image formatted in html like:
const string ERROR_IMAGE = "<img src=\"...\" alt=\"\" />";
in the View Action you can do something like this:
if(Something is Ine error)
ModelState.AddModelError(Something, ERROR_IMAGE);
Related
This is how I tried to create custom HTML helper and generate an id to it
but when I use the tag in my razor, I'm getting the same id for all tags when rendered, some one help me to find solution.
public static MvcHtmlString MyLabel(this HtmlHelper html, string text)
{
var builder = new TagBuilder("myLable");
builder.GenerateId("MyLableId1");
builder.SetInnerText(text);
return MvcHtmlString.Create(builder.ToString(TagRenderMode.Normal));
}
In Razor
#using MvcAppCustomeHtmlHelpers.Helper;
#Html.MyLabel("username")
#Html.TextBox("username")<br/>
#Html.MyLabel("password")
#Html.TextBox("password")
when I render text box the id is username and password for other textbox , but I'm unable to get id like text box for my custome html helper
Just pass one more parameter "id".
public static MvcHtmlString MyLabel(this HtmlHelper html, string text, string id)
{
var builder = new TagBuilder("myLable");
builder.GenerateId(id);
builder.SetInnerText(text);
return MvcHtmlString.Create(builder.ToString(TagRenderMode.Normal));
}
Now, you can use:
#Html.MyLabel("username", "label1")
#Html.MyLabel("username", "label2")
You want TagBuilder.GenerateId:
builder.GenerateId(text);
To be honest, this is nothing that a quick Google couldn't have told you:
http://www.asp.net/mvc/tutorials/older-versions/views/using-the-tagbuilder-class-to-build-html-helpers-cs
I have some Customer Details and I only want to show fields which have a value.
For example if Telephone is null don't show it.
I currently have in my view model
public string FormattedTelephone
{
get { return string.IsNullOrEmpty(this.Telephone) ? " " : this.Telephone; }
}
And in my view
#Html.DisplayFor(model => model.FormattedTelephone)
This is working correctly, however, I would like to show the Field Name if the field has a value e.g.
Telephone: 02890777654
If I use #Html.DisplayNameFor in my view it shows the field name even if the field is null.
I also want to style the field name in bold and unsure of where I style it - the view or the view model.
For the bold style you can use this bit of code in your view, but of course it's proper to use an external style sheet.
<style type="text/css">
.telephone{
font-weight: bold;
}
</style>
You can do the check for null in your view and conditionally display the data:
#if (Model.FomattedTelephone != null)
{
<div class="telephone">
#Html.DisplayFor(model => model.FormattedTelephone)</div>
}
For style add a class for to the span you can put around field name.
You could create your own HtmlHelper that will only write if string is not null or empty.
Or you could add a DisplayTemplates something like here:
How do I create a MVC Razor template for DisplayFor()
For more background on helpers in razor read the following
http://weblogs.asp.net/scottgu/archive/2011/05/12/asp-net-mvc-3-and-the-helper-syntax-within-razor.aspx
And if they're in your App_Code folder read the answer to this
Using MVC HtmlHelper extensions from Razor declarative views
You'll probably want to over the default helper page with this (and inherit in your helper classes in App_Code)
public class WorkaroundHelperPage : HelperPage
{
// Workaround - exposes the MVC HtmlHelper instead of the normal helper
public static new HtmlHelper Html
{
get { return ((WebViewPage)WebPageContext.Current.Page).Html; }
}
public static UrlHelper Url
{
get { return ((WebViewPage) WebPageContext.Current.Page).Url; }
}
}
I would make a helper for this, something like this:
using System.Web.Mvc.Html;
public static class HtmlHelpers
{
public static MvcHtmlString LabelDisplayFor<TModel, TValue>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expression)
{
StringBuilder html = new StringBuilder();
string disp = helper.DisplayFor(expression).ToString();
if (!string.IsNullOrWhiteSpace(disp))
{
html.AppendLine(helper.DisplayNameFor(expression).ToString());
html.AppendLine(disp);
}
return MvcHtmlString.Create(html.ToString());
}
}
Now, when you are in your View, you can simply do this (given you include the namespace in your view or web.config):
#Html.LabelDisplayFor(model => model.FormattedTelephone)
All it really does is check to see if your display helper is not an empty string, if it is, it will simply append your LabelFor and DisplayFor, if not, it will return an empty string.
I usually prefer to use Display/Editor Templates instead of HtmlHelper. Here is template that I have used to perform exactly the same task, its designed for bootstrap data list but anyone can adjust it easily.
#if (Model == null)
{
#ViewData.ModelMetadata.NullDisplayText
}
else if (ViewData.TemplateInfo.TemplateDepth > 1)
{
#ViewData.ModelMetadata.SimpleDisplayText
}
else
{
<dl class="dl-horizontal">
#foreach (var prop in ViewData.ModelMetadata.Properties.Where(pm => pm.ShowForDisplay && !ViewData.TemplateInfo.Visited(pm)))
{
if(MvcHtmlString.IsNullOrEmpty(Html.Display(prop.PropertyName)))
{
continue;
}
if (prop.HideSurroundingHtml)
{
#Html.Display(prop.PropertyName)
}
else
{
<dt>#prop.GetDisplayName()</dt>
<dd>#Html.Display(prop.PropertyName)</dd>
}
}
</dl>
}
Key line is:
if(MvcHtmlString.IsNullOrEmpty(Html.Display(prop.PropertyName)))
Its based on object template so to use it you need use it on object or whole model like
#Html.DisplayForModel("TemplateName")
I'm trying to create an html helper to render a button. As an example this needs to contain -
<button onClick="window.location='/Users/Edit/admin'">
I have tried to do this using TagBuilder but am having issues because MergeAttribute is encoding the html.
e.g.
buttonBuilder.MergeAttribute("onClick", "window.location='" + url.Action(action, controller, routeValues));
gives me -
<button onClick="window.location='/Users/Edit/admin">
Is there a way I can do this so it's not encoded? Or should I be using another method other than TagBuilder?
--EDITED
I almost forget, use the HtmlDecode:
public static class ButtonHelper
{
public static IHtmlString Button(this HtmlHelper html)
{
TagBuilder button = new TagBuilder("button");
button.MergeAttribute("onClick", "window.location='/Users/Edit/admin'");
return new HtmlString(System.Web.HttpUtility.HtmlDecode(button.ToString()));
}
}
Or look it: http://forums.asp.net/t/1377957.aspx/1
I have a label as
<%= Html.Label("");%>
i want to add content to label at runtime, unfortunately it doesn't take any other parameter to create id property for it. can't i create id property for it just similar to asp:label
thanks,
michaeld
No need to use the HtmlHelper functions always and everywhere if they don't fit your need. They're just supposed to make your life easier, not harder. Use good ole HTML here:
<label id="id_for_label"></label>
If you want to keep using HtmlHelper functions you can always create your own extension methods.
For example:
public static class LabelHelper
{
private static string HtmlAttributes(object htmlAttributes)
{
var builder = new StringBuilder();
foreach (PropertyDescriptor descriptor in
TypeDescriptor.GetProperties(htmlAttributes))
{
builder.AppendFormat(" {0}=\"{1}\" ", descriptor.Name,
descriptor.GetValue(htmlAttributes));
}
return builder.ToString();
}
public static MvcHtmlString MyLabel(this HtmlHelper htmlHelper,
string labelText, object htmlAttributes)
{
var attributes = HtmlAttributes(htmlAttributes);
return MvcHtmlString.Create(
String.Format("<label for=\"{0}\" {1}>{0}</label",
labelText, attributes.Trim()));
}
}
Then you can add a label to a view in the following manner:
<%: Html.MyLabel("Hello, World!", new { #id = "myLabel" })%>
The generated HTML is:
<label for="Hello, World!" id="myLabel">Hello, World!</label>
For MVC 3 such a helper function is already available:
http://msdn.microsoft.com/en-us/library/gg538318(v=VS.99).aspx
How can I make up a RouteLink in a custom HtmlHelper? I know how to make it in a partial view but I want to build up a new link in a custom htmlhelper extension method with the use of a RouteLink. How to accomplish this?
Update: I noticed HtmlHelper.GenerateRouteLink. But what do I need to put in as parameters?
Here's an example. Let's suppose that you want to wrap the links into a div tag with some given class so that your resulting html looks like this:
<div class="foo">Some text</div>
You could write the following extension method:
public static class HtmlExtensions
{
public static MvcHtmlString CustomRouteLink(
this HtmlHelper htmlHelper,
string className,
string linkText,
object routeValues
)
{
var div = new TagBuilder("div");
div.MergeAttribute("class", className);
div.InnerHtml = htmlHelper.RouteLink(linkText, routeValues).ToHtmlString();
return MvcHtmlString.Create(div.ToString());
}
}
which could be used like this:
<%= Html.CustomRouteLink("foo", "Some text",
new { action = "index", controller = "home" }) %>
and this will produce the desired markup. Any other overloads of RouteLink could be used if necessary.
Once you get an instance of the UrlHelper you should be able to do whatever you want to do in your HtmlHelper method
UrlHelper url = new UrlHelper(helper.ViewContext.RequestContext);