I thought this would have been easy but I am having issues ticking all the boxes that I need in this.
I need to
Serialize an object to Json
Ignore any properties not set
Use the ENum names instead of integer values
I have generated all the models for this using the Open API Generator based on a .yaml spec.
My first attempt was to get a bit of code from what looks like an old serializer
let json<'t> (myObj:'t) =
use ms = new MemoryStream()
let serialiser: DataContractJsonSerializer = new DataContractJsonSerializer(typeof<'t>)
let settings: DataContractJsonSerializerSettings = new DataContractJsonSerializerSettings()
(new DataContractJsonSerializer(typeof<'t>)).WriteObject(ms, myObj)
Encoding.Default.GetString(ms.ToArray())
This function actually does everything fine - except it copiess the enum numbers instead of names and I can't see an option to make this happpen.
My other attempt is using System.Text.Json.JsonSerializer:
let options
= new JsonSerializerOptions(
)
options.DefaultIgnoreCondition <- JsonIgnoreCondition.WhenWritingDefault
options.Converters.Add(new JsonStringEnumConverter(JsonNamingPolicy.CamelCase))
let jsonString:string = JsonSerializer.Serialize(shipmentRequest, options)
I have tried a few different things ( including excluding the Enum converter ) and I always get the following error.
Unable to cast object of type 'System.Int32' to type
'System.Nullable`1[Zimpla.Model.ExpressPackageReference+TypeCodeEnum]'
The specific Object ( roughly ) that it is having an issue with is:
[DataContract(Name = "ExpressPackageReference")]
public partial class ExpressPackageReference : IEquatable<ExpressPackageReference>, IValidatableObject
{
......etc
[DataMember(Name = "typeCode", EmitDefaultValue = false)]
public TypeCodeEnum? typeCode
{
get{ return _typeCode;}
set
{
_typeCode = value;
_flagtypeCode = true;
}
}
This particular property is not even set so it should be skipping over it theoretically. It is possible that I am not generating the object correctly
Without understanding all the details here, I think you are asking how you can serialize an object to json while omitting all properties that are null using System.Text.Json.
To accomplish that you have to set the following option:
options.IgnoreNullValues <- true
Here are the docs for this option:
https://learn.microsoft.com/en-us/dotnet/api/system.text.json.jsonserializeroptions.ignorenullvalues?view=net-5.0#System_Text_Json_JsonSerializerOptions_IgnoreNullValues
I have the following razor code that I want to have mm/dd/yyyy date format:
Audit Date: #Html.DisplayFor(Model => Model.AuditDate)
I have tried number of different approaches but none of that approaches works in my situation
my AuditDate is a DateTime? type
I have tried something like this and got this error:
#Html.DisplayFor(Model => Model.AuditDate.Value.ToShortDateString())
Additional information: Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions.
Tried this:
#Html.DisplayFor(Model => Model.AuditDate.ToString("mm/dd/yyyy"))
No overload for method 'ToString' takes 1 arguments
If you use DisplayFor, then you have to either define the format via the DisplayFormat attribute or use a custom display template. (A full list of preset DisplayFormatString's can be found here.)
[DisplayFormat(DataFormatString = "{0:d}")]
public DateTime? AuditDate { get; set; }
Or create the view Views\Shared\DisplayTemplates\DateTime.cshtml:
#model DateTime?
#if (Model.HasValue)
{
#Model.Value.ToString("MM/dd/yyyy")
}
That will apply to all DateTimes, though, even ones where you're encoding the time as well. If you want it to apply only to date-only properties, then use Views\Shared\DisplayTemplates\Date.cshtml and the DataType attribute on your property:
[DataType(DataType.Date)]
public DateTime? AuditDate { get; set; }
The final option is to not use DisplayFor and instead render the property directly:
#if (Model.AuditDate.HasValue)
{
#Model.AuditDate.Value.ToString("MM/dd/yyyy")
}
I have been using this change in my code :
old code :
<td>
#Html.DisplayFor(modelItem => item.dataakt)
</td>
new :
<td>
#Convert.ToDateTime(item.dataakt).ToString("dd/MM/yyyy")
</td>
If you are simply outputting the value of that model property, you don't need the DisplayFor html helper, just call it directly with the proper string formatting.
Audit Date: #Model.AuditDate.Value.ToString("d")
Should output
Audit Date: 1/21/2015
Lastly, your audit date could be null, so you should do the conditional check before you attempt to format a nullable value.
#if (item.AuditDate!= null) { #Model.AuditDate.Value.ToString("d")}
Googling the error that you are getting provides this answer, which shows that the error is from using the word Model in your Html helpers. For instance, using #Html.DisplayFor(Model=>Model.someProperty). Change these to use something else other than Model, for instance: #Html.DisplayFor(x=>x.someProperty) or change the capital M to a lowercase m in these helpers.
You can use the [DisplayFormat] attribute on your view model as you want to apply this format for the whole project.
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]
public Nullable<System.DateTime> Date { get; set; }
#ChrisPratt's answer about the use of Display Template is wrong. The correct code to make it work is:
#model DateTime?
#if (Model.HasValue)
{
#Convert.ToDateTime(Model).ToString("MM/dd/yyyy")
}
That's because .ToString() for Nullable<DateTime> doesn't accept Format parameter.
For me it was enough to use
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}")]
public DateTime StartDate { set; get; }
I implemented the similar thing this way:
Use TextBoxFor to display date in required format and make the field readonly.
#Html.TextBoxFor(Model => Model.AuditDate, "{0:dd-MMM-yyyy}", new{#class="my-style", #readonly=true})
2. Give zero outline and zero border to TextBox in css.
.my-style {
outline: none;
border: none;
}
And......Its done :)
You could use Convert
<td>#Convert.ToString(string.Format("{0:dd/MM/yyyy}", o.frm_dt))</td>
In View Replace this:
#Html.DisplayFor(Model => Model.AuditDate.Value.ToShortDateString())
With:
#if(#Model.AuditDate.Value != null){#Model.AuditDate.Value.ToString("dd/MM/yyyy")}
else {#Html.DisplayFor(Model => Model.AuditDate)}
Explanation: If the AuditDate value is not null then it will format the date to dd/MM/yyyy, otherwise leave it as it is because it has no value.
After some digging and I ended up setting Thread's CurrentCulture value to have CultureInfo("en-US") in the controller’s action method:
Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");
Here are some other options if you want have this setting on every view.
About CurrentCulture property value:
The CultureInfo object that is returned by this property, together
with its associated objects, determine the default format for dates,
times, numbers, currency values, the sorting order of text, casing
conventions, and string comparisons.
Source: MSDN CurrentCulture
Note: The previous CurrentCulture property setting is probably optional if the controller is already running with CultureInfo("en-US") or similar where the date format is "MM/dd/yyyy".
After setting the CurrentCulture property, add code block to convert the date to "M/d/yyyy" format in the view:
#{ //code block
var shortDateLocalFormat = "";
if (Model.AuditDate.HasValue) {
shortDateLocalFormat = ((DateTime)Model.AuditDate).ToString("M/d/yyyy");
//alternative way below
//shortDateLocalFormat = ((DateTime)Model.AuditDate).ToString("d");
}
}
#shortDateLocalFormat
Above the #shortDateLocalFormat variable is formatted with ToString("M/d/yyyy") works. If ToString("MM/dd/yyyy") is used, like I did first then you end up having leading zero issue. Also like recommended by Tommy ToString("d") works as well. Actually "d" stands for “Short date pattern” and can be used with different culture/language formats too.
I guess the code block from above can also be substituted with some cool helper method or similar.
For example
#helper DateFormatter(object date)
{
var shortDateLocalFormat = "";
if (date != null) {
shortDateLocalFormat = ((DateTime)date).ToString("M/d/yyyy");
}
#shortDateLocalFormat
}
can be used with this helper call
#DateFormatter(Model.AuditDate)
Update, I found out that there’s alternative way of doing the same thing when DateTime.ToString(String, IFormatProvider) method is used. When this method is used then there’s no need to use Thread’s CurrentCulture property. The CultureInfo("en-US") is passed as second argument --> IFormatProvider to DateTime.ToString(String, IFormatProvider) method.
Modified helper method:
#helper DateFormatter(object date)
{
var shortDateLocalFormat = "";
if (date != null) {
shortDateLocalFormat = ((DateTime)date).ToString("d", new System.Globalization.CultureInfo("en-US"));
}
#shortDateLocalFormat
}
.NET Fiddle
Maybe try simply
#(Model.AuditDate.HasValue ? Model.AuditDate.ToString("mm/dd/yyyy") : String.Empty)
also you can use many type of string format like
.ToString("dd MMM, yyyy")
.ToString("d") etc
This is the best way to get a simple date string :
#DateTime.Parse(Html.DisplayFor(Model => Model.AuditDate).ToString()).ToShortDateString()
Instead of
#Html.DisplayFor(Model => Model.AuditDate)
Use
#Model.AuditDate.ToString("MM/dd/yyyy")
This style renders the date as: 06/02/2022.
You can style your string accordingly to how you need it.
I had a similar issue on my controller and here is what worked for me:
model.DateSigned.HasValue ? model.DateSigned.Value.ToString("MM/dd/yyyy") : ""
"DateSigned" is the value from my model
The line reads, if the model value has a value then format the value, otherwise show nothing.
Hope that helps
You can use this instead of using #html.DisplayFor().
#Convert.ToString(string.Format("{0:dd/MM/yyyy}", Model.AuditDate))
You just need To set Data Annotation in your Model.
[DisplayFormat(ApplyFormatInEditMode = true,DataFormatString = "{0:MM/dd/yyyy}")]
public DateTime AuditDate {get; set;}
On view(cshtml page)
#Html.DisplayFor(model => model.AuditDate)
Nothing else you need to do.
Hope its useful.
See this answer about the No overload for method 'ToString' takes 1 arguments error.
You cannot format a nullable DateTime - you have to use the DateTime.Value property.
#Model.AuditDate.HasValue ? Model.AuditDate.Value.ToString("mm/dd/yyyy") : string.Empty
Tip: It is always helpful to work this stuff out in a standard class with intellisense before putting it into a view. In this case, you would get a compile error which would be easy to spot in a class.
This is my controller action:
<EmployeeAuthorize()>
Function HRA_Table() As ActionResult
' get current employee's id
Dim db1 As EmployeeDbContext = New EmployeeDbContext
Dim user1 = db1.Tbl_Employees.Where(Function(e) e.Employee_EmailAddress = User.Identity.Name).Single()
Dim empId = user1.Employee_ID
Dim empSSN = user1.Employee_SSN
Dim hra = db.Tbl_HRAs.Where(Function(x) x.SSN = empSSN)
Return View(hra.ToList)
End Function
This is my model:
Public Class Tbl_HRA
<Key()> Public Property HRA_ID() As Integer
Public Property SSN() As String
Public Property Height() As Double
Public Property Weight() As Double
Public Property Nic_EE() As String
Public Property Nic_SP() As String
Public Property BMI() As Double
Public Property BP_S() As Double
Public Property BP_D() As Double
Public Property HDL() As Double
Public Property LDL() As Double
Public Property Tot_Chol() As Double
Public Property Continine() As String
Public Property Glucose() As Double
Public Property Waist() As Double
Public Property Hip() As Double
Public Property Triglycerides() As Double
Public Property A1C() As Double
Public Property LDL_HDL() As Double
End Class
This is my view:
#ModelType IEnumerable(Of GemcoBlog.Tbl_HRA)
#Code
Layout = Nothing
End Code
#For Each item In Model
#item.Height
Next
The error I get is:
The 'Height' property on 'Tbl_HRA' could not be set to a 'String'
value. You must set this property to a non-null value of type
'Double'.
I can't seem to understand why this error is occurring. I tried changing it to double based on some articles I read, but still it won't work!
Thanks for your help.
From your comment, it appears that the column in the table is a varchar. As a result, your model must define it as a string. Try changing the height property to be as follows:
Public Property Height() As String
Unfortunately, you can't do type conversions directly in the LINQ to SQL implementation. If you want, you could project into another type (in the Select clause), but you would still need the immediate fetch (context.GetTable(Of T)) to have the types be equivalent between your database and the model.
This article might be of use - looks like an issue with your database schema? Is this column set as nullable in table?
http://digitaltoolfactory.net/blog/2012/03/how-to-fix-yet-another-you-must-set-this-property-to-a-non-null-value-of-type-double-problem-with-entity-framework/
i think this will help you
<ul>
#For Each g As MvcApplication1.Genre In Model
#<li>#g.Name</li>
Next
</ul>
and also see this url for more help
http://www.asp.net/web-pages/tutorials/basics/asp-net-web-pages-visual-basic
It looks like this could be caused by this database. It looks like they set these to varchar instead of double which is not ideal.
I'm using the option Label string for my Html.DropDownList but my datasource is a SelectList. How I would check for the option label back on the server? The backing type for the variable is an EnumType. I inspected the value and it says 0 but it won't let me check for 0.
Thanks,
rod.
How about casting the value back to the enum type on the server:
[HttpPost]
public ActionResult Index(int selectedValue)
{
MyEnum label = (MyEnum)selectedValue;
...
}
You can't. Labels aren't posted with the form. You'll need to place the value in a <input type="hidden"> if you want the value.
With MVC 2's addition of the HtmlHelper EditorFor() it is not possible to create strongly typed Display and Editor templates for a given Model object and after fiddling with it I am a bit stumped as to how to pass additional Model data to the editor without losing the strong-typing of the editor control.
Classic Example: Product has Category. ProductEditor has a DropDownList for Category containing the names of all Categories. The ProductEditor is strongly typed to Product and we need to pass in the SelectList of Categories as well as the Product.
With a standard view we would wrap the Model data in a new type and pass that along. With the EditorTemplate we lose some of the standard functionality if we pass in a mixed Model containing more than one object (first thing I noticed was all of the LabelFor/TextBoxFor methods were producing entity names like "Model.Object" rather than just "Object").
Am I doing it wrong or should Html.EditorFor() have an additional ViewDataDictionary/Model parameter?
You can either create a custom ViewModel which has both properties OR you'll need to use ViewData to pass that information in.
I am still learning, but I had a similar problem for which I worked out a solution.
My Category is an enum and I use a template control which examines the enum to determine the contents for the Select tag.
It is used in the view as:
<%= Html.DropDownList
(
"CategoryCode",
MvcApplication1.Utility.EditorTemplates.SelectListForEnum(typeof(WebSite.ViewData.Episode.Procedure.Category), selectedItem)
) %>
The enum for Category is decorated with Description attributes to be used as the text values in the Select items:
public enum Category
{
[Description("Operative")]
Operative=1,
[Description("Non Operative")]
NonOperative=2,
[Description("Therapeutic")]
Therapeutic=3
}
private Category _CategoryCode;
public Category CategoryCode
{
get { return _CategoryCode; }
set { _CategoryCode = value; }
}
The SelectListForEnum constructs the list of select items using the enum definition and the index for the currently selected item, as follows:
public static SelectListItem[] SelectListForEnum(System.Type typeOfEnum, int selectedItem)
{
var enumValues = typeOfEnum.GetEnumValues();
var enumNames = typeOfEnum.GetEnumNames();
var count = enumNames.Length;
var enumDescriptions = new string[count];
int i = 0;
foreach (var item in enumValues)
{
var name = enumNames[i].Trim();
var fieldInfo = item.GetType().GetField(name);
var attributes = (DescriptionAttribute[])fieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), false);
enumDescriptions[i] = (attributes.Length > 0) ? attributes[0].Description : name;
i++;
}
var list = new SelectListItem[count];
for (int index = 0; index < list.Length; index++)
{
list[index] = new SelectListItem { Value = enumNames[index], Text = enumDescriptions[index], Selected = (index == (selectedItem - 1)) };
}
return list;
}
The end result is a nicely presented DDL.
Hope this helps. Any comments about better ways to do this will be greatly appreciated.
Try using ViewData.ModelMetadata this contains all of your class Annotations.
Excellent article http://bradwilson.typepad.com/blog/2009/10/aspnet-mvc-2-templates-part-4-custom-object-templates.html