.net mvc Display field in view only if it has a value - asp.net-mvc

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")

Related

Creating a HtmlHelper to display content if certain conditions are fulfilled

I want to create a simple HtmlHelper to that I can use like this:
#using(Html.DisplayIf(Object object))
{
...
}
I tried the method suggested here, but unlike the guy who asked that question I would like the content between the brackets not to be rendered at all, not just hidden.
Is there a way to prevent the textwriter from writing the content between the brackets, or some other method that would be appropriate to solve my problem?
Edited
You can use the method described here: Capture wrapped content in BeginForm style disposable html helper.
I've applied the first method to your example.
public static class HtmlExtensions
{
public static HelperResult DisplayIf(this HtmlHelper html, Func<object, HelperResult> template, bool show)
{
return new HelperResult(writer =>
{
if (show)
{
template(null).WriteTo(writer);
}
});
}
}
You can call it like this:
#* Will render *#
#Html.DisplayIf(
#<span>test1</span>, true
)
#* Will not render *#
#Html.DisplayIf(
#<span>test2</span>, false
)

MVC 5 custom HtmlHelper for lightweight content editing

After years of working with WebForms I recently started the transition to MVC. I'm trying to create a plugable, lightweight content editing module but I've run into some problems.
The idea is simple: create a HtmlHelper named EditableSimpleHtml that can be used in a #using... { } syntax so that the following can be achieved in a razor view:
#using (Html.EditableSimpleHtml("MyKey"))
{
<h3>Test</h3>
<p>
1<br />
</p>
}
The value between the {...} is the default value for when no content can not be found in the data storage.
I've create a HtmlHelper. Below is a simplified version:
public static IDisposable EditableSimpleHtml(this HtmlHelper helper, string key)
{
// Get the content from the data storage using the key (I will not show the provider itself, its just a provider that will access a db)
var provider = ContentEditing.Provider;
string value = provider.GetValue(key);
if (value == null)
{
// No value found in the data storage for the supplied key, we have to use the default value from within the #using... { } statement
// Can I get that value here? I want to to store it initialy in the data storage
value = "..."; // How to get html from within the #using... { }?
}
return new ContentEditableHtmlString(helper, value);
}
public class ContentEditableHtmlString : IDisposable
{
private readonly HtmlHelper _helper;
public ContentEditableHtmlString(HtmlHelper helper, string value)
{
_helper = helper;
var builder = new TagBuilder("div");
var writer = _helper.ViewContext.Writer;
writer.Write(builder.ToString(TagRenderMode.StartTag));
writer.Write(value);
}
public void Dispose()
{
_helper.ViewContext.Writer.Write("</div>");
}
}
The problem is that I can't get the (default) content from within the #using... { } statement in the HtmlHelper, or at least I don't know how. I need it in case I want to store it to the database initially.
Second problem is that the value between the #using... { } statement will always be rendered. In the case when the content can be loaded from the data storage I want the default value to be replaced with the value from the data storage.
Is there a way to achieve this or did I start of on a completely wrong path?
You can not get the html within the #using{...} statement the way you are doing right now.
The closest thing you can do is use Templated Razor Delegates
public static HelperResult EditableSimpleHtml(this HtmlHelper helper, string key,
Func<string, HelperResult> template)
{
var templateResult = template(null);
//you have your value here that you can return directly
//or you can return HelperResult to write to the response directly
var templateResultHtml = templateResult.ToHtmlString();
return new HelperResult(writer =>
{
templateResult.WriteTo(writer);
});
}
And in your view:
#Html.EditableSimpleHtml("MyKey", #<text>
<h3>Test</h3>
<p>#DateTime.Now</p>
</text>)

how to add content to html.label in javascript asp.net mvc

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

MVC 3 multiple DisplayFor-Templates

I'm trying to make a custom template for a basket item list. I need a few different templates, as I have different ways of displaying the item, depending on if it's on the webpage or in a mail. Now my problem is, that when I use the default name it works flawlessly.
#Html.DisplayFor(b => b.Items)
But when I try to add a template name, I get an expection that my templates needs to be of a list type IEnumerable and not BasketItem.
#Html.DisplayFor(i => basket.Items, "CustomerItemBaseList")
Any ideas where my mistake is, or why it's not possible are appreciated. Thanks.
Unfortunately that's a limitation of templated helpers. If you specify a template name for a collection property the template no longer applies automatically for each item of the collection. Possible workaround:
#for (int i = 0; i < Model.Items.Length; i++)
{
#Html.DisplayFor(x => x.Items[i], "CustomerItemBaseList")
}
That's a good idea, Darin. I'm lazy though, so I'd like to take it one step further and make an actual helper that wraps this. I also took out the lambda expression to simplify it for my case, but you can easily add that functionality back in.
public static class DisplayTextListExtension
{
public static MvcHtmlString DisplayForList<TModel>(this HtmlHelper<TModel> html, IEnumerable<string> model, string templateName)
{
var tempResult = new StringBuilder();
foreach (var item in model)
{
tempResult.Append(html.DisplayFor(m => item, templateName));
}
return MvcHtmlString.Create(tempResult.ToString());
}
}
Then the actual usage looks like:
#Html.DisplayForList(Model.Organizations, "infoBtn")
I liked Dan's answer but just adjusted slightly as it can work for any IEnumerable:
using System.Collections;
using System.Text;
using System.Web.Mvc;
using System.Web.Mvc.Html;
namespace YourProject.Whatever
{
public static class DisplayExtensions
{
public static MvcHtmlString DisplayForIEnumerable<TModel>(this HtmlHelper<TModel> html, IEnumerable model, string templateName)
{
var tempResult = new StringBuilder();
foreach (var item in model)
{
var item1 = item;
tempResult.Append(html.DisplayFor(m => item1, templateName));
}
return MvcHtmlString.Create(tempResult.ToString());
}
}
}
And of course:
#Html.DisplayForIEnumerable(Model.Organizations, "NameOfYourDisplayTemplate")
I suggest another solution useful even more with lists of heterogeneous objects (i.e. BasketItem subclasses), using the additionalViewData parameter of the DisplayFor method, like:
#DisplayFor(b=>b.Items, new { layout="row" })
in this way the helper works fine with IEnumerable<T>, calling for each item (subclass of T) the relative DisplayTemplate, passing it the additionalViewData values in the ViewData dictionary.
The template could so output different code for different layout values.
In the example above the template named View\Shared\DisplayTemplates\BasketItem (or the name of the subclass) should be like this:
#model MyProject.BasketItem // or BasketItem subclass
#{
string layout = ViewData["layout"] as string ?? "default";
switch(layout)
{
case "row":
<div class="row">
...
</div>
break;
// other layouts
...
default: // strongly recommended a default case
<div class="default-view>
...
</div>
break;
}
}
It is strongly recommended to provide always a default code.
I hope this suggestion could help.

ASP.NET MVC: Page-specific logic

There has been many discussion on ASP.NET MVC and Codebehind-files, mostly where it has been pointed out that these Codebehind-files are evil.
So my question is, how do you handle page-specific logic?
What we don't want here is spaghetti-code in the inline-code and we don't want page-specific code scattered throughout helper-classes or on top of the HTML-helper-class.
An example would be:
<% for(int i = 0; i < companyList.Count; i++) { %>
RenderCompanyNameWithRightCapsIfNotEmpty(company, i)
<% } %>
With accompanying codebehind:
private string RenderCompanyNameWithRightCapsIfNotEmpty(string company, index)
{
if (index == 0) {
return string.Format("<div class=\"first\">{0}</div>", company);
}
// Add more conditional code here
// - page specific HTML, like render a certain icon
string divClass = (index % 2 == 0) ? "normal" : "alternate";
return string.Format("<div class=\"{1}\">{0}</div>", company, divClass);
}
This will only be used on one page and is most likely subject to change.
Update: A couple approaches I thought about where these:
1) Inline codebehind on page - with simple methods that returns strings.
<script runat="server">
private string RenderCompanyHtml(string companyName) ...
<script>
2) Putting a method which returns a string in the Controller. But that would be putting View-logic into the Controller.
public class SomeController : Controller
{
[NonAction]
private static string RenderCompanyHtml(string companyName) ...
public ActionResult Index() ...
}
You should put that code in the controlleraction where you prepare the viewdata.
I usually make a region "helper methods" in my controller class with a few [NonAction] methods to keep things clean.
So my (simplified) controller would look like this:
public class SomeController : Controller
{
#region Helper methods
[NonAction]
private static string CompanyNameWithRightCapsIfNotEmpty(string company)
{
if (string.IsNullOrEmpty(company)) {
return company;
}
return UpperCaseSpecificWords(company);
}
#endregion
public ActionResult Companies()
{
var companies = GetCompanies();
var companyNames = companies.Select(c => CompanyNameWithRightCapsIfNotEmpty(c.Name));
ViewData["companyNames"] = companyNames;
return view();
}
}
Helper methods are one good way of handling page specific code, but I think it is a;ways preferable to get your model to show the data you need.
If you're going to go for the helper option, you would be better served by making the operation it perfroms a bit less page specific. If your method RenderCompanyNameWithRightCapsIfNotEmpty has to be so specific it would be better if your model provided it. One way would be to have the model provide a list with the text already formatted, and expose it as a public property (say an IEnumerable of formatted company names).
Use Html Helpers.
Like so create the helper methods in a static class:
public static string Label(this HtmlHelper helper, string target, string text)
{
return String.Format("<label for='{0}'>{1}</label>", target, text);
}
.. then use in your view:
<span><% =Html.Label("FinishDateTime.LocalDatetime", "Finish Time:")%><br />
You could create a helper method called maybe RenderCompanyName(string[] companies) that checked for nulls, did the caps manipulation and rendered the html in between - all in the same helper if you like.
Also: controller action methods should be light - ie. only getting the data and returning views. You should delegate things like manipulation of data for presentation to views and Html helpers.
EDIT: Here is a helper that you might be after:
This helper renders an IList<> to html in the form of an unordered list <ul>...</ul>. The useful thing about it is that it gives you control over how the list is rendered thru css AND it allows you to render additional html/content for each item. Take a look - this is the helper:
public static string UnorderedList<TItem>(this HtmlHelper helper,
IList<TItem> items, Func<TItem, string> renderItemHtml,
string ulID, string ulClass, string liClass)
{
StringBuilder sb = new StringBuilder();
// header
if (!ulID.IsNullOrTrimEmpty()) sb.AppendFormat("<ul id='{0}'", helper.Encode(ulID.Trim()));
else sb.AppendFormat("<ul");
if (!ulClass.IsNullOrTrimEmpty()) sb.AppendFormat(" class='{0}'>", helper.Encode(ulClass.Trim()));
else sb.AppendFormat(">");
// items
foreach (TItem i in items)
{
if (!liClass.IsNullOrTrimEmpty())
sb.AppendFormat("<li class='{0}'>{1}</li>", helper.Encode(liClass.Trim()),
renderItemHtml(i));
else
sb.AppendFormat("<li>{0}</li>", renderItemHtml(i));
}
// footer
sb.AppendFormat("</ul>");
return sb.ToString();
}
..using it is easy. here is a simple example to render a list of tags:
<div id="tags">
<h2>Tags</h2>
<%=Html.UnorderedList<Tag>(Model.Tags.Tags,tag=>
{
return tag.Name;
},null,null,null) %>
</div>
..you can see in my usage example that i have chosen not to specify any css or id attribute and i simply return the name of the Tag item thru the use of the anonymous delegate. Anonymous delegates are way easy to use.. in your case maybe something like this would work:
<div id="tags">
<h2>Tags</h2>
<%=Html.UnorderedList<string>(ViewData["companies"],company=>
{
if (someCondition) return company.ToUpper();
else return company;
},null,null,null) %>
</div>
.. ViewData["companies"] is an IList<string> for simplicity.

Resources