简体   繁体   中英

Get specific table depending on week ASP.NET MVC LINQ

as the title says. I'am trying to get data out of the database depending on the week which the logged in user chooses.

My database table stampings has has an UserId, Timestamp and StampingType columns!

Model:

public partial class StampingModel
{
    [Key]
    [Column(Order = 0)]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int UserId { get; set; }

    [Key]
    [Column(Order = 1)]
    public DateTime Timestamp { get; set; }

    [Required]
    [StringLength(3)]
    public string StampingType { get; set; }

    public virtual User User { get; set; }
}

}

View:

@model Aviato.Models.StampingModel <input type="text" id="weekTxtBox"/> <input type="submit" value="Choose" id="weekStampBtn"/>

Controller:

public ActionResult GetWeekStamp(StampingModel model)
    {
        var getWeek = db.Stampings.FirstOrDefault(s => s.Timestamp == model.Timestamp); //This I dont quite know.

        return View();
    }

    public ActionResult Stampings()
    {
        return View();
    }

JavaScript (Optional, if there is an easier way, please let me know):

$("#weekStampBtn").click(function() {

    var weekTxtBox = $("#weekTxtBox").val();

    $.ajax({
        url: "User/GetWeekStamp",
        type: "POST",
        datatype: "json",
        data: {
            weekTxtBox: weekTxtBox
        }
    });

});

How should my coode look like? Especially my LINQ/Lambda expression...

Implement a method that gives you the week of the year:

private int GetWeekOfYear(DateTime d)
        {
            var cal = System.Globalization.DateTimeFormatInfo.CurrentInfo.Calendar;
            return cal.GetWeekOfYear(new DateTime(d.Year, d.Month, 1), System.Globalization.CalendarWeekRule.FirstDay, System.DayOfWeek.Sunday);
        }

and then change your code to:

var getWeek = db.Stampings.FirstOrDefault(s => GetWeekOfYear(s.Timestamp) == GetWeekOfYear(model.Timestamp)); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM