How to use DataAnnotations Display attribute for multiple radio button lables - asp.net-mvc-5

It's handy to use a Display attribute for model properties in MVC:
Model:
[Display(Name="Your Name:")]
public string Name { get; set; }
View:
#Html.LabelFor(m => m.Name)
#Html.EditorFor(m => m.Name)
But ... is it possible to use the Display attribute for naming the individual choices for radio buttons? The following is what I use now, but the 'Label for...' tag is a little inconsistent with the rest of the view. Anyone?
<div class="radio-inline">
#Html.RadioButtonFor(m => m.OpenToPublic, true, new { id = "isOpenToPublic" })
<label for="isOpenToPublic">Open to the Public</label>
</div>
<div class="radio-inline">
#Html.RadioButtonFor(m => m.OpenToPublic, false, new { id = "isInviteesOnly" })
<label for="isInviteesOnly">Invitees Only</label>
</div>
I like the code above, since using the Label tag results in being able to click on the label text to select the radio button, and the styling of the text is correct. I just wonder if there's a way to do this with data annotations on the model's property for the radio button.
Thanks,
Brian

Related

MVC 5 / Bind dropdownlist including disabled values

(My first quesion, I'm quite impressed :) )
First, please excuse my English, I'm French ;)
My issue is about DropDownList which is linked(bind) to a required field (F, int) of an object O (edited in a view V) and contains a list of elements (LE), some of them disabled.
The behavior I want in the view :
when I create an object, the validation must trigg if nothing
is selected in the list (OK)
when I create an object, the disabled elements of the list must not be selectable (OK)
when I edit an object, if the field is among enabled values, same behavior (OK)
when I edit an object, if the field is among disabled values, it must be displayed and selected when viewed (OK)
when I edit an object, if the field is among disabled values, when I post data, the client validation must authorize disabled values to be validated (OK with a little javascript)
My issue :
when I edit an object, if the field is among disabled values, when I
post data, the model contains null for the field linked to the
dropdownlist even if I include an hidden field with the Id.
Here is some of my code to help understand my issue.
Any idea of how I could include disabled values of my dropdown list in the model when I post data ?
Thanks for any help !
View :
<div class="col-md-3">
#Html.DropDownListFor(model => model.Currency.Id, (SelectList)ViewBag.Currencies, new { #class = "form-control ignore-desactivated" })
#Html.ValidationMessageFor(model => model.Currency, "", new { #class = "text-danger" })
</div>
JS :
$(function () {
$('form').validate().settings.ignore = '.ignore-desactivated';
});
Source when edition :
<div class="col-md-3">
<select class="form-control ignore-desactivated" data-val="true" data-val-number="The field Id must be a number." data-val-required="The Id field is required." id="Currency_Id" name="Currency.Id">
<option value="-1"></option>
<option disabled="disabled" value="9">Angolan kwanza (desactivated)</option>
<option value="10">Argentine peso</option>
<option disabled="disabled" selected="selected" value="1">Euro (desactivated)</option>
<option disabled="disabled" value="56">Gibraltar pound (desactivated)</option>
<option value="3">Great Britain Pound</option>
</select>
<span class="field-validation-valid text-danger" data-valmsg-for="Currency" data-valmsg-[replace][1]="true"></span>
</div>
My model when I want to save data :
https://i.stack.imgur.com/jQ9aH.png
... and I found an answer a few minutes after asking it (thanks to my colleagues)...
I don't know if that's correct, but a little js code to remove disabled items before the post did the trick :
//Delete disabled elements of lists before submit
$('form').submit(function () {
$('.ignore-desactivated').each(function () {
$(this).children().each(function () {
$(this).removeAttr('disabled');
});
})
})

MVC Validation on Subviews

I am working on a Sitecore/MVC application, my first MVC application so I am learning as I go. No doubt I am going wrong somewhere along the line.
I have a Basket that has 2 address views on it, one for billing and another for delivery. There is also a checkbox for "Delivery the same as billing" allowing the user to complete just one address. When you user checks this checkbox the delivery address div collapses.
Main view:
<div class="pure-control-group">
<h2>Billing Address</h2>
#Html.Action("Init", "Address", new {AddressType = "Billing", #Address = Model.Billing})
</div>
<!-- Delivery Address-->
<div class="pure-control-group">
<h2>Delivery Address</h2>
<label for="UseBillingForShipping" class="pure-checkbox">
#Html.CheckBoxFor(x => x.UseBillingForShipping)
Same as Billing Address above
</label>
</div>
<div class="manual-address-entry focus-pane">
#Html.Action("Init", "Address", new {AddressType = "Delivery", #Address = Model.Delivery})
</div>
An example of the Address view:
<div class="pure-u-1 pure-u-sm-1-2 pure-u-lg-2-5">
<label for="#(Model.AddressType).FirstName">First Name<span class="required">*</span></label>
<input type="text" id="#(Model.AddressType).FirstName" name="#(Model.AddressType).FirstName">
#Html.ValidationMessageFor(x=>x.FirstName) //<= How to handle this?
</div>
<div class="pure-u-1 pure-u-sm-1-2 pure-u-lg-2-5">
<label for="#(Model.AddressType).LastName">Last Name<span class="required">*</span></label>
<input type="text" id="#(Model.AddressType).LastName" name="#(Model.AddressType).LastName">
#Html.ValidationMessageFor(x=>x.LastName) //<= How to handle this?
</div>
My problem occurs when I am trying to validate. The id of the controls on the address view are named id="#(Model.AddressType).LastName" so in the case of the Billing address they render like id="Billing.LastName"
On the Address model the fields are annotated, e.g:
[Required(ErrorMessage = "First Name is required")]
public string FirstName { get; set; }
[Required(ErrorMessage = "Last Name is required")]
public string LastName { get; set; }
So I have 2 problems:
How do I create the #Html.ValidationMessageFor markup. I have tried #Html.ValidationMessageFor(x=>x.FirstName) and something similar to the labelfor (<label for="#(Model.AddressType).LastName">), #Html.ValidationMessageFor(#(Model.AddressType).LastName) and neither work. I am starting to think I have approached this totally the wrong way.
The second is if the user selects the checkbox for same address how would I go about switching off validation for the second address only.
The easiest way to handle this is to use a custom EditorTemplate for your address model. Assuming its public class Address, then create a view in /Views/Shared/EditorTemplates named Address.cshtml (i.e. named to match the name of your type)
#model yourAssembly.Address
#Html.LabelFor(m => m.FirstName)
#Html.TextBoxFor(m => m.FirstName)
#Html.ValidationMessageFor(m => m.FirstName)
... // ditto for other properties of Address
Then in the main view
#Html.EditorFor(m => m.Billing)
#Html.CheckBoxFor(x => x.UseBillingForShipping)
#Html.EditorFor(m => m.Delivery)
The EditorFor() method will use your template and correctly name all elements for binding (including the validation message)
Note that because you have a [Required] attribute, the script that hides the 'Delivery' address, should also ensure that it copies the contents of the 'Billing' to the 'Delivery' address controls otherwise validation will fail (alternatively you could use a [RequiredIf] validation attribute)

Binding an editor template for Kendo grid

I am having difficulties in wiring up a custom EditorTemplate to a grid within an MVC 5 application. I have an integer field that only accepts a 1 or 2 as a value. Rather than using a standard numeric text box or slider control, I'd like to wire this up using buttons (via Bootstrap's group buttons). If the user clicks on the first button, the value should be set to 1, otherwise it should be set to 2.
The problem that I'm experiencing is that when the user clicks on the "edit" button, the "Level" value never gets applied to the editor template. The template displays as I'd like, but I cannot figure out how to bind the selected value back to the Kendo grid. When the user clicks on the "save" button on the grid, the controller action is never invoked.
If I replace the editor template with a standard Kendo control such as a numeric text box or Kendo slider, it works fine.
ViewModel
public class LotViewModel
{
public int LotId { get; set; }
[Display(Name = "Level")]
[Range(1, 2)]
[UIHint("LotLevel")]
public int Level { get; set; }
}
View
#(Html.Kendo().Grid<LotViewModel>()
.Name("lotGrid")
.Columns(columns =>
{
columns.Bound(x => x.LotId).Visible(false);
columns.Bound(x => x.Level);
columns.Command(command =>
{
command.Edit();
}).Width(100);
})
.ToolBar(toolbar => toolbar.Create())
.Editable(editable => editable.Mode(GridEditMode.InLine))
.AutoBind(true)
.DataSource(dataSource => dataSource
.Ajax()
.Model(model =>
{
model.Id(m => m.LotId);
model.Field(m => m.Level).DefaultValue(1);
})
.Read(update => update.Action("GetLots", "Lot"))
.Create(update => update.Action("CreateLot", "Lot"))
.Update(update => update.Action("UpdateLot", "Lot"))
)
)
EditorTemplate: LotLevel
#model int
#{
var levelOne = Model.Equals(1) ? "active btn-primary" : null;
var levelTwo = Model.Equals(2) ? "active btn-primary" : null;
var htmlField = ViewData.TemplateInfo.HtmlFieldPrefix;
}
#Html.HiddenFor(model => model)
<div class="btn-group btn-group-#htmlField">
<button type="button"
class="btn btn-default #levelOne bool-#htmlField"
onclick="javascript: setValue(this, 1);">
Level 1
</button>
<button type="button"
class="btn btn-default #levelTwo bool-#htmlField"
onclick="javascript:setValue(this, 2);">
Level 2
</button>
</div>
<script>
function setValue(button, level) {
$('.btn-group-#htmlField button.active').removeClass('active btn-primary');
$(button).addClass('active btn-primary');
$('##htmlField').val(level); // TODO: Set the value of the model here
}
</script>
It comes down to binding. The editor template is instantiated once (with an empty model object) when the grid is created and then hidden. When you click "Edit" the editor is placed into the DOM, replacing the display row, and the values in the dataSource object are bound to the inputs in the editor template (by name, I think). With standard or kendo inputs this causes the editor to update and display the correct value. With a complex editor (or a complex object) the binding essentially fails and goes no further.
In your case, you can add an event handler to the Grid's edit event that will force the button to update to the input value when the editor is shown.

How to edit a custom DisplayWithIdFor?

I have created a DisplayWithIdFor using the following code and it works showing the information I wish it to.
public static class DisplayWithIDHelper
{
public static MvcHtmlString DisplayWithIdForApplication<TModel, TValue>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expression, string wrapperTag = "div")
{
var id = helper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(ExpressionHelper.GetExpressionText(expression));
return MvcHtmlString.Create(string.Format("<{0} style=\"color: #003F51; margin-left: 87px;\" class=\"{1}\">{2}</{0}>", wrapperTag, id, helper.DisplayFor(expression)));
}
}
My problem is simple, when I use the custom helper I end up with the label saying Application and the displayfor holding the name of the application showing with no space between them. see below.
Lastly here is the code for the image above:
<form>
<fieldset>
<p>
#Html.LabelFor(model => model.changeStatus.usersName)
#Html.DisplayFor(model => model.changeStatus.usersName)
#Html.HiddenFor(model => model.changeStatus.usersName)
#Html.ValidationMessageFor(model => model.changeStatus.usersName)
</p>
<p style="display: inline; float: left">
#Html.LabelFor(model => model.changeStatus.application)
#Html.DisplayWithIdForApplication(model => model.changeStatus.application)
#Html.HiddenFor(model => model.changeStatus.application)
#Html.ValidationMessageFor(model => model.changeStatus.application)
</p>
<p>
#Html.LabelFor(model => model.changeStatus.reasons)
#Html.TextAreaFor(model => model.changeStatus.reasons, new { #cols = "80", #rows = "4", #class = "k-textbox" })
<span style="color: red;"> #Html.ValidationMessageFor(model => model.changeStatus.reasons)</span>
</p>
<!-- Allow form submission with keyboard without duplicating the dialog button -->
<input type="submit" tabindex="-1" style="position:absolute; top:-1000px">
</fieldset>
</form>
Can anyone explain how to add the spacing between the two Html Helpers?
any additional code can be supplied like the Jquery popup code.
Thank you.
Edit:
Just to make things a little clearer I have to get the application name from the row of a kendo grid that is selected and set the name in the jquery using the following code:
$("div[class='changeStatus_application']").html(applicationName);
To simplify and ensure everything is acting the same, remove the:
style="display: inline; float: left"
from the second paragraph tag and use an element like a span instead of a div (block level element) in your helper.
You may then want to alter the margin left on your DisplayWithIDHelper.
Also try using classes instead of style attributes. You can then change the look of your site through your style sheet without having to recompile plus styles are centralised; easier to maintain.

Orchard cms Extending Menu Item part

What's the best way to extent the Menu part in orchard ?
I want to use the normal menu part for most content types.
But I also want a Custom MainNavigationMenuPart. that has all the things the menu part has but adds a media picker field and a text field to it. - These items that will display on menu rollover.
Option 1
I think this is the best way to go ...
I've looked at writing a custom Menu part - but it seem like a lot of functionality for how the menu part currently work is there, I'm not sure how best to tap into this in a DRY way.
I can add a MenuPartItem to my customPart, so main menu part model would look like this
public class MainMenuPart : ContentPart<MainMenuRecord>
{
public MenuPart MenuPart { get; set; }
public string ShortDescription
{
get { return Record.ShortDescription; }
set { Record.ShortDescription = value; }
}
}
But ...
how do I render this on in the editor view for the part ?
I want to use the exiting MenuPartItemEditor.
how do I save this information in the record for the part?
Option 2
I've looked also at adding fields to the menu part (via cms).
My menu part now looks like this on the back end
Here I have customise the admin view for the menu depending on the content type.
Buy creating a Parts.Navigation.Menu.Edit.cshtml in Views/EditorTemplates, in my custom them I have access to the menu part, but I can seem to control the display of the fileds I have added to the part. (menu image, highlight, and short description)
Here is the custom Parts.Navigation.Menu.Edit.cshtml (original found in Orchard.Core/Navigation/Views/EditorTemplates/Parts.Navigation.Menu.Edit.cshtml)
#model Orchard.Core.Navigation.ViewModels.MenuPartViewModel
#using Orchard.ContentManagement
#using Orchard.Core.Navigation.Models;
#if (!Model.ContentItem.TypeDefinition.Settings.ContainsKey("Stereotype") || Model.ContentItem.TypeDefinition.Settings["Stereotype"] != "MenuItem")
{
if (Model.ContentItem.ContentType == "StandardIndexPage" ||
Model.ContentItem.ContentType == "AlternateIndexPage" ||
Model.ContentItem.ContentType == "MapIndexPage")
{
var sd = ((dynamic)Model.ContentItem).MenuPart.ShortDescription;
#sd
<fieldset>
#Html.HiddenFor(m => m.OnMenu, true)
#Html.HiddenFor(m => m.CurrentMenuId, Model.CurrentMenuId)
<div>
<label for="MenuText">#T("Menu text (will appear on main menu)")</label>
#Html.TextBoxFor(m => m.MenuText, new { #class = "text-box single-line" })
<span class="hint">#T("The text that should appear in the menu.")</span>
</div>
</fieldset>
}
else
{
<fieldset>
#Html.EditorFor(m => m.OnMenu)
<label for="#Html.FieldIdFor(m => m.OnMenu)" class="forcheckbox">#T("Show on menu")</label>
<div data-controllerid="#Html.FieldIdFor(m => m.OnMenu)" class="">
<select id="#Html.FieldIdFor(m => m.CurrentMenuId)" name="#Html.FieldNameFor(m => m.CurrentMenuId)">
#foreach (ContentItem menu in Model.Menus)
{
#Html.SelectOption(Model.CurrentMenuId, menu.Id, Html.ItemDisplayText(menu).ToString())
}
</select>
<span class="hint">#T("Select which menu you want the content item to be displayed on.")</span>
<label for="MenuText">#T("Menu text")</label>
#Html.TextBoxFor(m => m.MenuText, new { #class = "text-box single-line" })
<span class="hint">#T("The text that should appear in the menu.")</span>
</div>
</fieldset>
}
}
else
{
<fieldset>
<label for="MenuText">#T("Menu text")</label>
#Html.TextBoxFor(m => m.MenuText, new { #class = "textMedium", autofocus = "autofocus" })
<span class="hint">#T("The text that should appear in the menu.")</span>
#Html.HiddenFor(m => m.OnMenu, true)
#Html.HiddenFor(m => m.CurrentMenuId, Request["menuId"])
</fieldset>
}
I've also tried to control the display of fields using the placement.info in the theme
<Match ContentType="StandardIndexPage">
<Place Fields_Boolean_Edit-Highlight="-"/>
</Match>
with no success.

Resources