I'm having some issues with a view model in my project that contains an number of doubles in them
ie.
public class MyViewModel
{
public double Left { get; set; }
public double Right { get; set; }
public double Top { get; set; }
public double Bottom { get; set; }
}
In my view I have
#Html.EditorForModel
If there is no other custom templates in my project this renders correctly and I get a textbox with a double on in it.
As soon as I put a string template in View/Shared/EditorTemplate and put anything inside of it whatever is in that template gets rendered instead of the double template.
I would have thought that even though I have overriden the string template the order for selecting templates would remain the same, and the double template would be choosen as it was originally before the string template existed.
The string template consisted of only (no #model )
<h2>String</h2>
Am I missing something here, why is the string template choosen here?
I've determined I can put a double template in the views shared folder and it will render that instead but it seems like I shouldn't have to do that.
EDIT:
As per Darin's answer I created my own double editortemplate based on the decimal template.
#using System.Globalization
#functions {
private object FormattedValue
{
get
{
if (ViewData.TemplateInfo.FormattedModelValue == ViewData.ModelMetadata.Model)
{
return String.Format(CultureInfo.CurrentCulture, "{0:0.00}", ViewData.ModelMetadata.Model);
}
return ViewData.TemplateInfo.FormattedModelValue;
}
}
}
#Html.TextBox("", FormattedValue, new {#class = "text-box single-line"})
Am I missing something here, why is the string template choosen here?
In both cases it's the String template being chosen. There's no default template for the double type. Here's how the default string template looks like:
#Html.TextBox(
"",
ViewData.TemplateInfo.FormattedModelValue,
new { #class = "text-box single-line" }
)
I've determined I can put a double template in the views shared folder
and it will render that instead but it seems like I shouldn't have to
do that.
Well, if you are not satisfied with the default template for the double type (which is string.cshtml) you could always write a custom template for it.
Related
I'm trying to create a ViewComponent that I can use with TagHelpers where I pass in an object as the parameter.
So, for example, I have this ViewComponent—which could end up having more parameters:
public IViewComponentResult Invoke(string? pageTitle, string? description, string? headerView)
And I'd like to do something like:
public class PageHeaderViewComponentOptions
{
public string pageTitle2;
public string Description;
}
public IViewComponentResult Invoke(PageHeaderViewComponentOptions phvc)
And use it like:
<vc:page-header phvc:page-title2="Test Title"></vc:page-header>
But, this isn't working.
I also tried explicitly setting the attribute information on the parameter class as follows:
[HtmlTargetElement("PageHeaderViewController")]
public class PageHeaderViewComponentOptions
{
[HtmlAttributeName("page-title")]
public string pageTitle2 { get; set; }
public string Description;
}
With no luck either.
My thought is that I could pass that object directly to the view. Typing this, I wonder if passing in the parameters separately and then assigning each to a member of a specific view model might be a better idea.
Any help here would be greatly appreciated.
In order to add an object as a parameter you'll need to pass an object.
This object can be created in the controller and passed as part of the view model, e.g.:
#model MyApp.MyViewModel
Where MyViewModel is something like:
public class MyViewModel
{
public PageHeaderViewComponentOptions PhvcOptions { get; set; }
}
And you pass the object like this:
<vc:page-header phvc="PhvcOptions"></vc:page-header>
Inside of a razor code block:
#{
var PhvcOptions = new PageHeaderViewComponentOptions
{
pageTitle2 = "Test Title";
};
}
Where you pass the object like this:
<vc:page-header phvc="#PhvcOptions"></vc:page-header>
Or even inline, which looks something like this:
<vc:page-header phvc="#(new PageHeaderViewComponentOptions { pageTitle2 = "Test Title" })"></vc:page-header>
Though that defeats the purpose and string input should be used instead:
<vc:page-header pageTitle2="Test Title"></vc:page-header>
The advantage of an object is that it may be null and fields of the object may be omitted. Where string parameters need to be present in the tag, even when empty.
Inserting objects is IMO also useful when you can use a part of the view model as a parameter, as shown above, or when the view model implements different interfaces and can therefore be passed as the parameter itself:
<vc:page-header phvc="Model"></vc:page-header>
Where MyViewModel is something like:
public class MyViewModel : IPageHeaderViewComponentOptions
{
public string pageTitle2 { get; set; }
}
And
public interface IPageHeaderViewComponentOptions
{
string pageTitle2;
}
I didn't test the code and there may be typos. Especially with the #. But you get the idea. Either approach should work.
I'm having problems with ASP.NET Core MVC and decimal? value.
I have the following view model:
public class BlobViewModel
{
public int Id { get; set; }
public int? IntegerValue { get; set; }
public string StringValue { get; set; }
[DataType(DataType.Date)]
public DateTime? DateValue { get; set; }
public decimal? DecimalValue { get; set; }
}
And the following input element in my view
<input asp-for="DecimalValue" class="form-control" />
When I enter a decimal value, e.g. "68.5" or "68,5" and tab out of the input element, I get the following error:
The value '68.5' is not valid for DecimalValue.
I have tried with the [DataType(DataType.Currency)] attribute above the property, but I can't seem to get the binding to work. The other properties binds as expected.
Does anyone have an idea for how I accomplish this?
The error you get occurs if you local Windows settings isn't set to US localization and you are using the default asp.net template jquery validation to validate decimal values. The errors should occur irrespective if your decimals are nullable or not
In ASP.NET Core I don't think you can force the localization to US in the web.config as you get in this answer in the same way you can for ASP.NET MVC5 and earlier, so you will have to add javascript to override the jquery.validate.js as mentioned as an answer to the same question.
create a js file called validationlocalization and put it in your wwwroot\js folder with the following contents
$.validator.methods.range = function (value, element, param) {
var globalizedValue = value.replace(",", ".");
return this.optional(element) || (globalizedValue >= param[0] && globalizedValue <= param[1]);
}
$.validator.methods.number = function (value, element) {
return this.optional(element) || /^-?(?:\d+|\d{1,3}(?:[\s\.,]\d{3})+)(?:[\.,]\d+)?$/.test(value);
}
In the cshtml pages that require decimal validation add a reference to the javascript file to your scripts section. Make sure it is added after an reference to the existing _ValidationScriptsPartial.
#section Scripts {
...
<script src="~/js/validationlocalization.js"></script>
More detail on this workaround
I have a simple class below that I am trying to use to display the Content string in the Editor Kendo Control. I am having issues binding the Property to the Editor. How can I bind the Content String to the Kendo UI Web/MVC Editor using Razor?
public class Details
{
public int TextId { get; set; }
public string Content { get; set; }
}
public List<Details> TextDetails
{
get
{
return mDetails;
}
}
#model MyApp.MyModels.ContentModel
#{
ViewBag.Title = "EditorContent";
}
<h2>Stuff To Display</h2>
#(Html.Kendo().Editor()
.Name("editor")
.Value(Model.TextDetails.Content)
//I thought I could just bind to the property.... How can I show the Content in the Editor?
)
You should do: Model.TextDetails.First().Content, Otherwise everything is fine. As you know Value() requires just a string value and renders as html content, providing appropriate model property (string) shouldn't hurt the editor.
I have a class
public class LookupClass {
public int Id { get; set; }
public string Name { get; set; }
}
That I have referenced in another class
public class Sampleclass {
public int Id { get; set; }
public LookupClass LookupEntry { get; set; }
}
which is is displayed in a KendoUI Grid
#(Html.Kendo().Grid<SampleClass>()
.Name("SomeGrid")
.Columns(cols => {
cols.Bound(o => o.LookupEntry).Title("Lookup Column") // Displays [object Object]
cols.Bound(o => o.LookupEntry.Name) // displays name correctly
}
.DataSource(datasource =>
// leaving this out since the data is seems to be loading correctly.
)
)
When displaying the grid it just displays [object Object] for the value in the cells in the "Lookup Column" column. I have gotten the editor template working (leaving out code since not necessary, basically copied from here) and saving/loading works (left out for simplicity), but I can't seem to figure out how to display the Name property from the Lookup class.
Found a KendoUI example that shows how to do this (http://demos.kendoui.com/web/grid/editing-custom.html)
Basically you have to use a ClientTemplate to display the property you want to display
#(Html.Kendo().Grid<SampleClass>()
.Name("SomeGrid")
.Columns(cols => {
cols.Bound(o => o.LookupEntry).ClientTemplate("#=LookupEntry.Name#").Title("Lookup Column")
}
)
On a side note, if you try to create a new record, it will produce an error about not finding LookupEntry (don't remember exact message). In the example listed, there is also a bit in the model section that shows how to set a default object.
I would like have a listbox of states render using the EditorForModel Html helper.
My view model:
public class MyViewModel
{
public MyewModel()
{
States = new SelectList(MyModel.RegionsToSelectList,"Value","Text");
}
[DataType(DataType.Text)]
public string City { get; set; }
[Display(Name = "States")]
public SelectList States { get; private set; }
}
In my view I have #Html.EditorForModel()
The City renders properly but the States do not render into any sort of list (dropdown or listbox)
If I use #Html.DropDownList("mylistname", Model.States) it renders properly.
I would really like to have it render in the ForModel process.
Can this be done?
You need to use the Html.DropdownListFor helper if you want to generate a drop down list. The fact that you have used SelectList as type to some of your properties doesn't mean that the default editor template will render a box. So you will have to write a custom editor template.
You may take a look at the following blog post to see how those default templates are implemented.