I have been trying to sort DateTime column in asp.net mvc webgrid.
Here is my code:
grid.Column(header: "Product Purchased Date",columnName:"PurchasedDate" canSort: true,format: #<text>
#item.PurchasedDate.ToString("MM/dd/yyy")</text>
when i tried using above code i am getting this errors:
cannot convert from 'lambda expression' to
'System.Func'
The best overloaded method match for System.Web.Helpers.WebGrid.Column(string, string, System.Func, string, bool)' has some invalid arguments.
if i apply the above code without using columName i am unable to perform sorting.
Apologize if i missed anything.
I'd recommend that, if you want to sort it as a string, add a function within your Model object that returns the value as a string instead of converting it inline. So there would be a field such as PurchasedDateAsString on the object.
For instance this is something I used in a recent project. The field DateRange is returned as a string and can be sorted upon just like it was a "base" field:
public class PeriodView
{
[Key]
public int PeriodId { get; set; }
public string Name { get; set; }
public int Number { get; set; }
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
public int Year { get; set; }
public string Month { get; set; }
public string DateRange
{
get
{
var start = String.Format("{1}-{0}",
CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(StartDate.Month).Substring(0, 3),
StartDate.Day);
var end = String.Format("{1}-{0}",
CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(EndDate.Month).Substring(0, 3),
EndDate.Day);
return String.Format("{0} to {1}", start, end);
}
}
}
If you convert DateTime to string and format it, the WebGrid will sort the column as a string, which is not correct for DateTime Format Column expected result.
Related
I have the following class:
public class ReturnDto
{
[Column("PARC_NUM")]
public int ParcelNumber { get; set; }
~[Column("CUSTOM_TAXE")] or [Column("AUTOMATIC_TAXE")]~
public decimal Taxe { get; set; }
}
I'm working in this Api using Dapper/Dommel and that class is supposed to be filled with the values from the data base. The problems is that it doesn't work for the second property (the "Taxe" one) because, as follows, the Query have two possible columns to take the value from:
...
ag.PARC_NUM AS ,
case when pp.IDT_MODALID = 3 then ag.CUSTOM_TAXE else ag.AUTOMATIC_TAXE end AS Taxe,
...
I tried setting the column name as Taxe (because that's how I name it, after all), but it just doesn't get mapped correctly. Actually, it just throws an exception poiting that such thing doesn't exist.
I am missing some standard setting or it just can't be done that way?
Try assign one of the valid column name
case when pp.IDT_MODALID = 3
then ag.CUSTOM_TAXE
else ag.AUTOMATIC_TAXE
end AS AUTOMATIC_TAXE ,
or add a field in the class
public class ReturnDto
{
[Column("PARC_NUM")]
public int ParcelNumber { get; set; }
~[Column("CUSTOM_TAXE")] or [Column("AUTOMATIC_TAXE")]~
public decimal Taxe { get; set; }
[Column("TAXE")]
public decimal Taxe { get; set; }
}
I am currently sending from SoapUI for my tests the following request:
<caja:GenerarObligacion>
<caja:Obligacion>
<obl:BenCheq>TALLERES ARROYO</obl:BenCheq>
<obl:CodMoneda>S/.</obl:CodMoneda>
<obl:CodProd>VM14</obl:CodProd>
<obl:CodRamo>AUTO</obl:CodRamo>
<obl:CodUsuario>ACSELP</obl:CodUsuario>
<obl:DptoEmi>000101</obl:DptoEmi>
<obl:FecFinVig>2024-02-28T12:00:01</obl:FecFinVig>
<obl:FecIniVig>2025-02-28T12:00:01</obl:FecIniVig>
<obl:FecMod>2026-07-17T13:02:05</obl:FecMod>
<obl:FecNotif>2026-07-17T13:02:05</obl:FecNotif>
<obl:FecOcurr>2025-01-28T08:41:53</obl:FecOcurr>
<obl:FecRecepDocPago>2025-01-28T00:00:00</obl:FecRecepDocPago>
<obl:IdePol>25000293961</obl:IdePol>
<obl:IdeSin>1500013900</obl:IdeSin>
<obl:IndCheque>S</obl:IndCheque>
<obl:ItemOblig>
<fac:BEDetalleObligacion>
<fac:CodCpto>DSCTOS</fac:CodCpto>
<fac:ItemDoc/>
<fac:FecFact>2025-01-28T00:00:00</fac:FecFact>
<fac:MtoCptoEgre>600.0</fac:MtoCptoEgre>
<fac:NroFact>444444444</fac:NroFact>
<fac:NumCpto>1</fac:NumCpto>
<fac:SerieFact>f045</fac:SerieFact>
<fac:TipoRegCompra>01</fac:TipoRegCompra>
</fac:BEDetalleObligacion>
<fac:BEDetalleObligacion>
<fac:CodCpto>ISLV</fac:CodCpto>
<fac:ItemDoc/>
<fac:FecFact>2025-01-28T00:00:00</fac:FecFact>
<fac:MtoCptoEgre>108.0</fac:MtoCptoEgre>
<fac:NroFact>444444444</fac:NroFact>
<fac:NumCpto>2</fac:NumCpto>
<fac:SerieFact>f045</fac:SerieFact>
<fac:TipoRegCompra>01</fac:TipoRegCompra>
</fac:BEDetalleObligacion>
</obl:ItemOblig>
<obl:MtoAprob>708.0</obl:MtoAprob>
<obl:NumAprob>18000493</obl:NumAprob>
<obl:NumPol>2500029396</obl:NumPol>
<obl:StsOblig>VAL</obl:StsOblig>
<obl:StsSin>ACT</obl:StsSin>
<obl:TasaCambio>1.0</obl:TasaCambio>
<obl:TipoAprob>P</obl:TipoAprob>
<obl:TipoBenef>TALR</obl:TipoBenef>
<obl:TipoDocPago>CHQ</obl:TipoDocPago>
</caja:Obligacion>
<caja:Tercero>
<ter:BETercero>
<ter:NumId>650606871</ter:NumId>
<ter:TipoId>J</ter:TipoId>
</ter:BETercero>
</caja:Tercero>
</caja:GenerarObligacion>
All the data arrives well except for the "FecFact" field, as seen in the request this field if it has a date but when arriving at the visual debug the following value "01/01/0001" is displayed:
In spite of sending a value to the FecFact field, it is set with the date that is displayed in the image "01/01/0001" as if the field were arriving null. This is the declaration of my entity.
[DataMember]
public String CodCtpo { get; set; }
[DataMember]
public DateTime FecFact { get; set; }
[DataMember] //IndIGV
public String IndnoGravado { get; set; }
[DataMember] //MtoCptoAprob
public Decimal MtoCptoEgre { get; set; }
[DataMember] // NumCpto - ?uso? NUMDETOBLIG
public Int32 NumCpto { get; set; }
[DataMember]
public String NroFact { get; set; }
[DataMember]
public String SerieFact { get; set; }
[DataMember]
public String TipoRegCompra { get; set; } //Funcional como OB
[DataMember]
public String CodSvcio { get; set; }
DateTime is initialized by default by DateTime.MinValue, which is actually 1/1/0001 12:00:00 AM exactly same as what you are getting.
You should declare nullable field if want null Date like:
DateTime? dt = null;
OR
Compare DateTime variables to DateTime.MinValue & set corresponding value in database query as null or in UI variable as null.
According to your description, I have restored your problem successfully,
The only thing you need to do is try to assign the NameSpace attribute to the DataContract Class.
[DataContract(Namespace ="mydomain")]
public class Product
{
[DataMember]
public int ID { get; set; }
[DataMember]
public DateTime dateTime { get; set; }
}
I hope this information is useful.
I want to execute a basic SQL query (e.g. "SELECT string FROM table WHERE criteria = TRUE) on MVC Entity Framework 6. The returned type is to be a string. I have tried many possible things but they return the SQL query string or something completely irrelevant, such as:
SELECT [Extent1].[Fname] AS [Fname]
FROM [dbo].[Developer] AS [Extent1]
WHERE ([Extent1].[Login] = #p__linq__0)
OR (([Extent1].[Login] IS NULL) AND (#p__linq__0 IS NULL))
I have the following in my controller:
var data = db.Developers.Where(y => y.Login.Equals(username)).ToList();
This is my Developers class:
public partial class Developer
{
public int PersonID { get; set; }
public string Fname
{
get { return Fname.ToString(); }
set { Fname = value;}
}
public string Lname { get; set; }
public string Developer1 { get; set; }
public string Login { get; set; }
public Nullable<bool> IsManager { get; set; }
public Nullable<bool> IsPF { get; set; }
public Nullable<bool> IsLW { get; set; }
public string Prov { get; set; }
}
I would like to get the string that this query returns.
Somehow this works when this is made to a List and passed to the View model, where it is displayed using #Html.DisplayFor().
Is there a way to execute my SQL command in my controller and get a string value in return?
FirstOrDefault() to return the first element, in this case there is only one.
You should include a validation if username doesnt exist.
Developer myDeveloper = db.Developers
.Where(y => y.Login.Equals(username))
.ToList()
.FirstOrDefault();
return myDeveloper.Lname;
I'm having issues with a date property not binding correctly using TryUpdateModel in MVC.
I am using a POCO class and a corresponding viewModel.
public class ContactModel
{
public int Id { get; set; }
[Display(Name = "First Name")]
[StringLength(50)]
[Required(ErrorMessage = "First name must be entered.")]
public string ContactGivenName { get; set; }
[Display(Name = "Last Name")]
[StringLength(50)]
[Required(ErrorMessage = "Last name must be entered.")]
public string ContactFamilyName { get; set; }
....
[Display(Name = "Date of Birth")]
public DateTime? DateOfBirth { get; set; }
}
the entity class:
public class Contact
{
[Key]
public int Id { get; set; }
[StringLength(50)]
[Column(TypeName = "varchar")]
public string ContactFamilyName { get; set; }
[StringLength(50)]
[Column(TypeName = "varchar")]
public string ContactGivenName { get; set; }
...
[Column(TypeName = "date")]
public DateTime? DateOfBirth { get; set; }
}
and in my controller :
[HttpPost]
[GridAction]
public virtual ActionResult UpdateContact(int id, FormCollection form)
{
//Find a customer whose CustomerID is equal to the id action parameter
var c = _contactService.Get(id);
if (c != null)
{
//Perform model binding (fill the customer properties and validate it).
if (TryUpdateModel(c, form))
{
The _contactService.Get returns the instance from EntityFramework.
The TryUpdateModel binds string properties like first and last name correctly, but despite a lot of tries, I can't get it to bind the date of birth.
I suspect it's a formatting issue of some kind but cannot find what it is.
When I debug, I can see in the FormCollection that the date is correctly there, with the value that was input in the view so the data is definitely passed on to the controller.
the value passed to the controller is in format :
yyyy-MM-dd
I tried modifying this on the fly with multiple format without success.
Any ideas what I'm doing wrong here ?
Thanks a lot
Well, first, I have no idea why you're using TryUpdateModel.. That's pretty archaic.
Second, it sounds to me like you have not set your culture to accept the format you expect. Add the following to your web.config if your browser is defaults already set to the correct culture:
<system.web>
<globalization culture="auto" uiculture="auto" enableclientbasedculture="true">
</globalization>
</system.web>
If you want to force a culture, then set the culture you wish in this setting.
the globalization didn't help and is actually already set, however I realized there's a custom binder for Datetime and that is probably where my problem is.
thanks
Using PetaPoco, I am running a fetch similar to this:
var result=db.Page<article>(1, 20, // <-- page number and items per page
"SELECT * FROM articles WHERE category=#0 ORDER BY date_posted DESC", "coolstuff");
where article is defined as
public class article
{
public long article_id { get; set; }
public string title { get; set; }
public DateTime date_created { get; set; }
public bool draft { get; set; }
public string content { get; set; }
}
But while result.TotalItems shows the correct number, result.Items does not contain anyting. I have also tried to decorate the definition of class article with
[PetaPoco.TableName("articles")]
[PetaPoco.PrimaryKey("article_id")]
and explicit column mapping
[PetaPoco.Column]
but result has always been the same. Is there a bug or what am I doing wrong?
Make sure that the page number starts from 1 and not 0. Its possible that in your code that you did not show here has that bug.