For my Project I want to access the database especially one table which has the BauTeilId in it and putting all the BauTeilId into one List in the Controller
DefaultConnection:
"DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=QualitätsKontrolleDB;Trusted_Connection=True;MultipleActiveResultSets=true"
Controller
The String Code is from the HTML and consits of 6 digits
private ApplicationDbContext Context = new ApplicationDbContext();
[HttpGet]
public IActionResult StartPage(string Code)
{
Debug.WriteLine(Code);
var list = Context.Result.All(c => c.BauTeilId);
return View();
}
Table used for this
I only need the BauTeilId
TypenID int
PruefungenID int
BildID int
BauTeilID string
Date DateTime
xLabel string
X int
YLabel string
Y int
FehlerCode string
Fehlername string
FehlerGruppe1 string
FehlerGruppe2 string
Result int
Right now the output is not existent but it should be the whole column.
If to want to get only BauTeilId from table likeselect BauTeilId from table use
(from t in Context.Result
select new {
t.BauTeilId
}).toList(); // .toList(); is not necessary, Linq returns an `IEnumerable `
That LINQ Statement,Hope you get point.
You can take list of any columns you want like this :
var myDynamicList = Context.Result.Select(c=> new { c.BauTeilId }).ToList();
this will be a List of dynamic type. For example you can call first element BauTeilId like this :
myDynamicList.First().BauTeilId;
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.
I want to make additional editor template for the Int32. In it I want to get all attributes(custom/default-data-annotations) and do some work with them:
#model Int32
#{
string propertyName = ViewData.ModelMetadata.PropertyName;
var attributes = ViewData.ModelMetadata.GetSomeHowAllTheAttributesOfTheProperty;
SomeWorkWithAttribute(attributes);
}
<input type="text" name="#propertyName" value="#ViewData.ModelMetadata.DisplayFormatString" class="form-control"/>
So the question how to get in the EditorTemplate all attributes of the property?
Thx in advance
EDIT: initial answer removed (not enough info in the question):
Since you need to access your custom attribute, I suggest the following:
A: if you're just saving some values using your custom attribute, use the AdditionalMetadataAttribute:
Model:
[Additional("myAdditionalInfoField", "myAdditionalInfoValue")]
public int IntProperty { get; set; }
View:
#{
string valueFromAttribute = ViewData.ModelMetadata.Additional["myAdditionalInfoField"].ToString();
}
B: if you're doing more complex work inside your custom attribute, get the current metadata property for your model and save the computed values inside the ViewData.ModelMetadata.Additional dictionary. Please note that this requires that you implement your custom metadata provider.
A detailed implementation can be found here.
this is how to access all the attributes in your model property from the DisplayTemplate or EditorTemplate:
var attributes = ((Microsoft.AspNetCore.Mvc.ModelBinding.Metadata.DefaultModelMetadata)ViewData.ModelMetadata).Attributes;
then you can get the desired custom attribute:
var yourAttribute = attributes.PropertyAttributes.OfType<YourAttribute>().FirstOrDefault();
now you have yourAttribute to do what ever you want!
I am trying to display empty string when model.EndDate is 0
#Html.DisplayFor(modelItem => model.EndDate)
I tried
#Html.DisplayFor(modelItem => model.EndDate == 0 ? "" : model.EndDate.ToString())
and
#Html.Display("End Date",model.EndDate == 0 ? "" : model.EndDate.ToString())
both did not worked for me. Both of the displaying empty when data is available.
Do a conditional outside the DisplayFor:
#if (Model.EndDate != 0)
{
Html.DisplayFor(modelItem => model.EndDate)
}
You can't compare a datetime to 0 in asp.net.
error CS0019: Operator `==' cannot be applied to operands of type `System.DateTime' and `int'
A DateTime is a value type so it get a default value of DateTime.MinValue when it isn't set.
using System;
public class Test {
public static DateTime badDate;
public static DateTime goodDate = DateTime.Now;
public static void Main(string[] args) {
Console.WriteLine(goodDate == DateTime.MinValue ? "" : goodDate.ToString());
Console.WriteLine(badDate == DateTime.MinValue ? "" : badDate.ToString());
}
}
How about this one ?
DateTime dt;
if (DateTime.TryParse("Your Date", out dt))
{
//Now you have validated the date
//Your code goes here
}
I think you should make your model property be a nullable type. So for example if its type is DateTime then declare the property as a nullable DateTime:
public DateTime? EndDate { get; set; }
this way instead of a 0 date (whatever that means) you will have no value. This also makes sense especially if this model property is coming from the database and is nullable.
You can read more about the nullable types here: http://msdn.microsoft.com/en-us/library/2cf62fcy(v=vs.80).aspx
I didn't like the answers given above because adding IF Statements to everything just slows your system down, in my case i needed to display a default string value several times in each row of a list view when the class property was a null value.
So have a look at the MS Docs here:
DisplayFormatAttribute.NullDisplayText Property
The following example shows how to use the NullDisplayText to define a caption to display when the data field is null.
// Display the text [Null] when the data field is empty.
// Also, convert empty string to null for storing.
[DisplayFormat(ConvertEmptyStringToNull = true, NullDisplayText = "[Null]")]
public object Size;
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.