I am working on asp.net MVC 5, I created a helper for boolean.
I wrote this:
public class CustomHelper
{
public static string Boolean(bool? value)
{
if(value == true )
return string.Format("<span class='glyphicon glyphicon-ok green'></span>");
else
return string.Format("<span class='glyphicon glyphicon-remove red'></span>");
}
}
and the Razor is:
<td>
#CustomHelper.Boolean(item.Deleted)
</td>
but the result is the same as the photo. the html appears as a string
how to fix it? so I can show the symbol instead?
thank you
By default, the # symbol encodes the output.
You should create your custom check as an extension method to the HtmlHelper class as below
public static class BooleanExtensions
{
public static MvcHtmlString Boolean(this HtmlHelper helper, bool value)
{
var spanTag = new TagBuilder("span");
if(value)
spanTag.MergeAttribute("class", glyphicon glyphicon-ok green");
else
spanTag.MergeAttribute("class", glyphicon glyphicon-remove red");
return MvcHtmlString.Create(spanTag.ToString(TagRenderMode.EndTag));
}
}
Next, in your Razor view, call it as:
#Html.Boolean(item.Deleted)
Don't forget to add the #using for the namespace that has the class in the beginning of the view
Related
In certain cases I want to display SelectList object not using DropDownListFor helper. Instead, I want to create a helper that iterates over the SelectListItems, and draw something different.
I have created an EditorTemplate:
#model RadioButtonOptions
<div class=" switch-field noselect" style="padding-left: 0px;">
#foreach (SelectListItem op in Model.Values.Items)
{
var idLabelF = ViewData.TemplateInfo.GetFullHtmlFieldId("") + "_" + op.Value;
var esChecked = "";
if (op.Selected)
{
esChecked = "checked";
}
<input type="radio" id="#idLabelF" name="#(ViewData.TemplateInfo.GetFullHtmlFieldName(""))" value="#op.Value" #esChecked />
<label for="#idLabelF" style="width: 100px;">#op.Text</label>
}
</div>
The RadioButtonOptions class is a ViewModel:
public class RadioButtonOptions
{
public SelectList Values { get; set; }
}
The final resul looks like this:
My ViewModel is like this (simplified):
public class MainVisitVM
{
public MainVisit Visit { get; set; }
public RadioButtonOptions VisitOptions { get; set; }
}
And I use it in Razor View as:
<div class="clearfix">
#Html.LabelFor(x=> x.Visit.Tipo)
<div class="input">
#Html.EditorFor(x=> x.VisitOptions ) //HERE
</div>
</div>
The problem I have is that I want this to work more like the DropDownListFor, so the lamda expresion I pass is the property holding the selected value, and then just pass the SelectList object (or a custom list).
<div class="clearfix">
#Html.LabelFor(x=> x.Visit.Tipo)
<div class="input">
#Html.CustomDropDownListFor(x=> x.Visit.Tipo, Model.VisitOptions ) //This would be ideal!!
</div>
</div>
So, I think doing this using EditorTemplates will not be possible.
Any idea in how to accomplish this?
Thanks to #StephenMuecke suggestion, I ended up with this HtmlHelper extension method:
public static MvcHtmlString RadioButtonForSelectList<TModel, TProperty>(
this HtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, TProperty>> expression,
SelectList listOfValues)
{
string htmlFieldName = ExpressionHelper.GetExpressionText(expression);
if (listOfValues == null) return MvcHtmlString.Create(string.Empty);
var wrapperDiv = new TagBuilder("div");
wrapperDiv.AddCssClass("switch-field noselect");
wrapperDiv.Attributes.Add("style", "padding-left: 0px;");
var sb = new StringBuilder();
foreach (SelectListItem item in listOfValues)
{
var idLabelF = htmlFieldName.Replace(".","_") + "_" + item.Value;
var label = htmlHelper.Label(idLabelF, item.Text, new { style = "width: 100px;" }).ToHtmlString();
var radio = htmlHelper.RadioButtonFor(expression, item.Value, new { id = idLabelF }).ToHtmlString();
sb.AppendFormat("{0}{1}", radio, label);
}
wrapperDiv.InnerHtml = sb.ToString();
return MvcHtmlString.Create(wrapperDiv.ToString());
}
Not particulary proud of my htmlFieldName.Replace(".","_"), but works.
I have the following code in a Razor Helper file
#helper MakeNoteBlank(string content)
{
string msg = "";
if(content == null)
{
msg = " ";
}
else
{
msg = content;
}
<div class="note">
<p>
#Html.Raw(msg)
</p>
</div>
}
The code fails at execution with the #Html.Raw(..) statement, stating that
"Object reference not set to an instance of an object."
If I remove the #Html.Raw(..) and output 'msg' directly then there is no problem.
What am I doing wrong?
use #(new HtmlString()) instead of #Html.Raw()
The best approach I can think of would possibly be creating an extension method for HtmlHelper. You need to create a class like this:
using System.Web;
using System.Web.Mvc;
namespace MyApplication.Extensions
{
public static class HtmlHelperExtension
{
public static IHtmlString DisplayMessage<T>(this HtmlHelper<T> htmlHelper, string content)
{
return htmlHelper.Raw($#"
<div class=""note"">
<p>
{content ?? " "}
</p>
</div>
");
}
}
}
Then in your cshtml file, simply use it like this:
#using MyApplication.Extensions;
#Html.DisplayMessage("Your content here")
Hope this helps.
Is there a way to convert the submit button with an ActionLink?
I got this ActionLink which redirects the user to the index page:
#Html.ActionLink("Cancel", "Index", null, new { #class = "k-button" })
And a save button which submits to save whatever is created or altered:
<input type="submit" value="Save" />
It would be nice to have the submit button the same code as the ActionLink.
You could use an <a> tag directly, try something like this:
<a onclick="$('#YourForm').submit();" class="k-button">Save</a>
And in your Action Post of your form:
[HttpPost]
public ActionResult Post(..)
{
/// process something...
return RedirectToAction("Index");
}
HTML Helper
As in the comments, you could create your own html helper, try this:
using System;
using System.Web.Mvc;
namespace MvcApplication.Helpers
{
public static class HtmlExtensions
{
public static string SubmitLink(this HtmlHelper helper, string text, string formId)
{
return string.Format("<a class='k-button' onclick='$(\"#{1}\").submit();'>{1}</a>", text, formdId);
}
}
}
And use it:
#Html.SubmitLink("Save", "formId")
In Asp.net MVC3 when you write below code , it generates wrapping html itself
#using (Html.BeginForm()) {
#Html.ValidationMessageFor(model => model.Text)
}
It generates codes in below format,
<form method="post" action="/Feeds">
<!-- Fields Here -->
</form>
My question in #using (Html.BeginForm()) automatically adds <form> tag at beginning and end, how can i create something like that of my own.
I am looking for some thing like below
#using (Html.BeginMYCUSTOMDIV())
{
I am text inside div
}
Expected Generated Output
<div class="customDivClass">
I am text inside div
</div>
Something along the lines:
public class MyDiv : IDisposable
{
private readonly TextWriter _writer;
public MyDiv(TextWriter writer)
{
_writer = writer;
}
public void Dispose()
{
_writer.WriteLine("</div>");
}
}
public static class MyExtensions
{
public static MyDiv BeginMYCUSTOMDIV(this HtmlHelper htmlHelper)
{
var div = new TagBuilder("div");
div.AddCssClass("customDivClass");
htmlHelper.ViewContext.Writer.WriteLine(div.ToString(TagRenderMode.StartTag));
return new MyDiv(htmlHelper.ViewContext.Writer);
}
}
and in the view:
#using (Html.BeginMYCUSTOMDIV())
{
<span>Hello</span>
}
generates:
<div class="customDivClass">
<span>Hello</span>
</div>
If I'm not mistaken, Html.BeginForm() returns an IDisposable object. When used in the using block, the object's Disposemethod is called, which is the responsible to write the closing tag to the output.
how does using HtmlHelper.BeginForm() work?
Html.BeginForm() type of extension
I have just started to discover FluentHml and I'm stuck with the CheckBoxList Helper.
Here is the code
<ul>
<%=this.CheckBoxList(m=>m.Filter)
.Options(criteria.Choices, x => x.Code, x => x.DisplayText)
.Selected(Model.Filter)
.Label(criteria.Label).ItemFormat("<li> {0} </li>")
%>
</ul>
So, I have a checkboxlist based on "criteria.Choices" which is typed as List<ChoiceViewModel>.
Here is the code of a ChoiceViewModel
public class ChoiceViewModel
{
// Some stuff
public string Code { get{ return _code; } }
public string Label { get { return _label; }}
public string DisplayText { get { return _displayText;}
}
}
And my problem is :
I want to disable the checkbox under a condition.
Let's say that if the Code doesn't start with an "A", I want to disable the checkbox
How can I achieve that ?
Thanks,
Hasan
CheckboxList does not provide that. You can do it with CheckBox in loop. Something like this:
<label>criteria.Label</label>
<%foreach (var choice in criteria.Choices) {%>
<li>
<%=this.CheckBox(m => m.Filter)
.Value(choice.Code)
.Checked(choice == Model.Filter)
.Label(choice.Code.DisplayText)
.Disabled(choice.Code.StartsWith("A")%>
</li>
<%}%>