简体   繁体   English

根据星期的ASP.NET MVC LINQ获取特定的表

[英]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! 我的数据库表标记具有UserId,Timestamp和StampingType列!

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): JavaScript(可选,如果有更简单的方法,请告诉我):

$("#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... 特别是我的LINQ / Lambda表达式...

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)); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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