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)
Related
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
I am not looking for a javascript/jquery answer. I can do that, but I feel like it breaks the purpose. This seems like something that should be possible without javascript.
I'm trying to get a simple listbox selection to update an #Html.Partial section, and I'm not exactly sure what to do. Everything loads initially just fine. After I submit, however, I am not quite sure how to 'attach' to my partial view to update it.
The purpose here is to only load the listbox one time, and let them view or request as many new reports as they want without reloading. If it's not possible, that's fine, I can use one page, reload the listboxes, and it will work. I just don't see why I would need to go to the database to reload the listbox items every time they view or request a report.
"master" html page:
#using TCTReports.Models
#model ReportViewModel
<h2>My Reports</h2>
<div class="row">
<div class="col-md-6">
<h3>Select Report</h3>
#using (Html.BeginForm("GetReport", "Report"))
{
#Html.DropDownListFor(m => m.SelectedMyID, Model.myLB)
<input type="submit" value="View" />
}
</div>
<div class="col-md-6">
<h3>All Reports</h3>
#using (Html.BeginForm("ReqReport", "Report"))
{
#Html.DropDownListFor(m => m.SelectedAllID, Model.allLB)
<input type="submit" value="View" />
}
</div>
</div>
#Html.Partial("_Msg")
_Msg is super simple atm. It would eventually be a report viewer, for now, it looks at #Viewbag...
<h2>#ViewBag.Message</h2>
Controller submit actions (I get my selected value just fine. currently on void but was ActionResult with Views - but I don't feel like that is correct either, as it completely overwrites the page (even with PartialView) and I lose my listboxes and _layout...):
public void GetReport(ReportViewModel model)
{
var myID = model.SelectedMyID;
ViewBag.Message = "Report: " + myID.ToString() + " Selected.";
//return PartialView("_Msg","Test");
}
public void ReqReport(ReportViewModel model)
{
var allID = model.SelectedAllID;
ViewBag.Message = "Report: " + allID.ToString() + " Requested.";
//return PartialView("_Msg", "Test");
}
Ok, so how would I go about updating _Msg and refreshing only the #Html.PartialView() section of my master html page? I played with #sections briefly but didn't make much progress.
(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');
});
})
})
I have an Address view for users to enter their addresses for both billing and shipping. So on the Address model I have:
public string AddressType { get; set; }
Then on the Create Account view I have:
<div class="pure-control-group">
#Html.Action("Init", "Address", new {AddressType="Billing"})
</div>
<div class="pure-control-group">
#Html.Action("Init", "Address", new {AddressType="Shipping"})
</div>
In the Address View I have a number of input controls that all render as expected but I also have a Country Dropdown List that I want to dynamically name (the only control I am using the html helper for):
#Html.DropDownListFor(m => m.SelectedCountryId, new SelectList(Model.ValidCountries, "CountryId", "CountryName", Model.SelectedCountryId), null, new {name=Model.AddressType + "_SelectedCountryId", id=Model.AddressType + "_SelectedCountryId"})
However when this renders I end up with:
<select id="Billing_SelectedCountryId" name="SelectedCountryId">
I want:
<select id="Billing_SelectedCountryId" name="Billing_SelectedCountryId">
I have read that using an upper case N for Name fixes this but as others have said it just adds another property:
<select id="Billing_SelectedCountryId" name="SelectedCountryId" Name="Billing_SelectedCountryId">
Everything I have read is a bit confusing and I can't make out if anyone found a fix, Is there anyway round this?
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.