Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/307.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在详细信息页面上记录导航_C#_Asp.net Mvc 3 - Fatal编程技术网

C# 在详细信息页面上记录导航

C# 在详细信息页面上记录导航,c#,asp.net-mvc-3,C#,Asp.net Mvc 3,我很确定我对这段代码的理解是正确的,但我想做的是在页面上用导航控件显示一条特定的记录,该控件允许您转到下一条和上一条记录(MVC3中生成的详细信息视图页面的修改版本) 当我导航到该页面时,代码通过ViewBag变量初始化ActionLink按钮,并在相应控制器中通过此方法进行设置 我的问题是,是否有更好的方法来执行以下操作,同时防止超出数据库记录的范围 public ViewResult Details(int id) { //Conditional Statements to mana

我很确定我对这段代码的理解是正确的,但我想做的是在页面上用导航控件显示一条特定的记录,该控件允许您转到下一条和上一条记录(MVC3中生成的详细信息视图页面的修改版本)

当我导航到该页面时,代码通过ViewBag变量初始化ActionLink按钮,并在相应控制器中通过此方法进行设置

我的问题是,是否有更好的方法来执行以下操作,同时防止超出数据库记录的范围

public ViewResult Details(int id)
{
    //Conditional Statements to manage navigation controls
    if (db.tblQuoteLog.OrderByDescending(x => x.LogDate).Any(x => x.nID < id))
    {
        //Set value next button
        ViewBag.NextID = id;

        ViewBag.PreviousID = db.tblQuoteLog.OrderByDescending(x => x.LogDate).FirstOrDefault(x => x.nID > id).nID; //Inverted logic due to orderby
    }
    else if (db.tblQuoteLog.OrderByDescending(x => x.LogDate).Any(x => x.nID > id))
    {
        ViewBag.NextID = db.tblQuoteLog.OrderByDescending(x => x.LogDate).FirstOrDefault(x => x.nID < id).nID; //Inverted logic due to orderby

        //Set value previous button
        ViewBag.PreviousID = id;
    }
    else
    {
        //Set value next button
        ViewBag.NextID = db.tblQuoteLog.OrderByDescending(x => x.LogDate).FirstOrDefault(x => x.nID < id).nID;

        //Set value previous button
        ViewBag.PreviousID = db.tblQuoteLog.OrderByDescending(x => x.LogDate).FirstOrDefault(x => x.nID > id).nID;
    }

    tblQuoteLog tblquotelog = db.tblQuoteLog.Find(id);

    return View(db.tblQuoteLog.Where(x => x.nID == id).FirstOrDefault());
}
公共视图结果详细信息(int-id)
{
//用于管理导航控件的条件语句
if(db.tblQuoteLog.OrderByDescending(x=>x.LogDate).Any(x=>x.nIDx.LogDate).FirstOrDefault(x=>x.nID>id).nID;//orderby导致的反向逻辑
}
else if(db.tblQuoteLog.OrderByDescending(x=>x.LogDate).Any(x=>x.nID>id))
{
ViewBag.NextID=db.tblQuoteLog.OrderByDescending(x=>x.LogDate).FirstOrDefault(x=>x.nIDx.LogDate).FirstOrDefault(x=>x.nIDx.LogDate).FirstOrDefault(x=>x.nID>id).nID;
}
tblQuoteLog tblQuoteLog=db.tblQuoteLog.Find(id);
返回视图(db.tblQuoteLog.Where(x=>x.nID==id.FirstOrDefault());
}
编辑 我对我的逻辑做了一个改变,这似乎与迈克给出的想法(可能不整洁,但更小)很好地吻合

//如果找不到任何记录,则EOF设置为true。
var nextRecord=(从db.tblQuoteLog中的r开始
orderby r.Quote\u ID递减
其中r.Quote_IDID
选择新的
{
Quote_ID=r.Quote_ID,
EOF=假
}).以(1)为例。
FirstOrDefault()??新的{Quote_ID=ID,EOF=true};
//用于管理导航控件的条件语句
如果((nextRecord.EOF==true))
{
//设置值下一步按钮
ViewBag.NextID=id;
ViewBag.PreviousID=previousRecord.Quote\u ID;
}
else if((previousRecord.EOF==true))
{
ViewBag.NextID=nextRecord.Quote\u ID;
//设置值上一个按钮
ViewBag.PreviousID=id;
}
其他的
{
//设置值下一步按钮
ViewBag.NextID=nextRecord.Quote\u ID;
//设置值上一个按钮
ViewBag.PreviousID=previousRecord.Quote\u ID;
}
错误检查现在通过使用注释类型在Linq查询中进行。我使用一个EOF(文件结束)标志,以便在找不到记录时,将ID设置为当前记录,并将EOF设置为true


谢谢大家的建议:)。

从id-1中选择前3名怎么样

    public ViewResult Details(int id)
{
    var items = db.tblQuoteLog.OrderByDescending(x => x.LogDate).Where(x => x.Id >= (id - 1)).Take(3);
}
  • 如果结果中有3项,则您将有上一项、下一项和当前项
  • 如果结果中有2项,则您的id是最后一页
  • 如果有1或0项,则您的id无效

可能需要更多的思考(例如,如果你的id<2怎么办),但这是一条潜在的路径

我认为这是一个很好的挑战,所以我打开笔记本电脑,尝试一下

我沿着我第一个答案的路线走,但实际上为了有2个查询而不是3个查询,它产生了大量糟糕的代码。所以我简化了它。如果在创建的Id列上都放置索引,那么应该可以很快工作

PageService是您要查看的类

class Program
{
    static void Main(string[] args)
    {
        Database.SetInitializer<MyDbContext>(null);

        var context = new MyDbContext(@"Data Source=.;Initial Catalog=Play;Integrated Security=True;");

        PageService service = new PageService(context);
        while (true)
        {
            Console.WriteLine("Please enter a page id: ");
            var pageId = Console.ReadLine();

            var detail = service.GetNavigationFor(Int32.Parse(pageId));

            if (detail.HasPreviousPage())
            {
                Console.WriteLine(@"Previous page ({0}) {1} {2}", detail.PreviousPage.Id, detail.PreviousPage.Name, detail.PreviousPage.Created);
            }
            else
            {
                Console.WriteLine(@"No previous page");
            }

            Console.WriteLine(@"Current page ({0}) {1} {2}", detail.CurrentPage.Id, detail.CurrentPage.Name, detail.CurrentPage.Created);


            if (detail.HasNextPage())
            {
                Console.WriteLine(@"Next page ({0}) {1} {2}", detail.NextPage.Id, detail.NextPage.Name, detail.NextPage.Created);
            }
            else
            {
                Console.WriteLine(@"No next page");
            }

            Console.WriteLine("");
        }


    }
}

public class PageService
{
    public MyDbContext _context;

    public PageService(MyDbContext context)
    {
        _context = context;
    }

    public NavigationDetails GetNavigationFor(int pageId)
    {
        var previousPage = _context.Pages.OrderByDescending(p => p.Created).Where(p => p.Id < pageId).FirstOrDefault();
        var nextPage = _context.Pages.OrderBy(p => p.Created).Where(p => p.Id > pageId).FirstOrDefault();
        var currentPage = _context.Pages.FirstOrDefault(p => p.Id == pageId);

        return new NavigationDetails()
        {
            PreviousPage = previousPage,
            NextPage = nextPage,
            CurrentPage = currentPage
        };
    }
}

public class NavigationDetails
{
    public Page PreviousPage { get; set; }
    public Page CurrentPage { get; set; }
    public Page NextPage { get; set; }

    public bool HasPreviousPage()
    {
        return (PreviousPage != null);
    }

    public bool HasNextPage()
    {
        return (NextPage != null);
    }
}

public class MyDbContext : DbContext
{
    public MyDbContext(string nameOrConnectionString)
        : base(nameOrConnectionString)
    {
    }

    public DbSet<Page> Pages { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Configurations.Add(new PageMap());
    }

}

public class PageMap : EntityTypeConfiguration<Page>
{

    public PageMap()
    {
        ToTable("t_Pages");

        Property(m => m.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
        Property(m => m.Name);
        Property(m => m.Created);
    }

}

public class Page
{
    public int Id { get; set; }
    public string Name { get; set; }
    public DateTime Created { get; set; }
}

无论是什么解决方案,我都建议您将该逻辑的allot移到服务类之后,这样您的操作方法就很精简了。
class Program
{
    static void Main(string[] args)
    {
        Database.SetInitializer<MyDbContext>(null);

        var context = new MyDbContext(@"Data Source=.;Initial Catalog=Play;Integrated Security=True;");

        PageService service = new PageService(context);
        while (true)
        {
            Console.WriteLine("Please enter a page id: ");
            var pageId = Console.ReadLine();

            var detail = service.GetNavigationFor(Int32.Parse(pageId));

            if (detail.HasPreviousPage())
            {
                Console.WriteLine(@"Previous page ({0}) {1} {2}", detail.PreviousPage.Id, detail.PreviousPage.Name, detail.PreviousPage.Created);
            }
            else
            {
                Console.WriteLine(@"No previous page");
            }

            Console.WriteLine(@"Current page ({0}) {1} {2}", detail.CurrentPage.Id, detail.CurrentPage.Name, detail.CurrentPage.Created);


            if (detail.HasNextPage())
            {
                Console.WriteLine(@"Next page ({0}) {1} {2}", detail.NextPage.Id, detail.NextPage.Name, detail.NextPage.Created);
            }
            else
            {
                Console.WriteLine(@"No next page");
            }

            Console.WriteLine("");
        }


    }
}

public class PageService
{
    public MyDbContext _context;

    public PageService(MyDbContext context)
    {
        _context = context;
    }

    public NavigationDetails GetNavigationFor(int pageId)
    {
        var previousPage = _context.Pages.OrderByDescending(p => p.Created).Where(p => p.Id < pageId).FirstOrDefault();
        var nextPage = _context.Pages.OrderBy(p => p.Created).Where(p => p.Id > pageId).FirstOrDefault();
        var currentPage = _context.Pages.FirstOrDefault(p => p.Id == pageId);

        return new NavigationDetails()
        {
            PreviousPage = previousPage,
            NextPage = nextPage,
            CurrentPage = currentPage
        };
    }
}

public class NavigationDetails
{
    public Page PreviousPage { get; set; }
    public Page CurrentPage { get; set; }
    public Page NextPage { get; set; }

    public bool HasPreviousPage()
    {
        return (PreviousPage != null);
    }

    public bool HasNextPage()
    {
        return (NextPage != null);
    }
}

public class MyDbContext : DbContext
{
    public MyDbContext(string nameOrConnectionString)
        : base(nameOrConnectionString)
    {
    }

    public DbSet<Page> Pages { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Configurations.Add(new PageMap());
    }

}

public class PageMap : EntityTypeConfiguration<Page>
{

    public PageMap()
    {
        ToTable("t_Pages");

        Property(m => m.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
        Property(m => m.Name);
        Property(m => m.Created);
    }

}

public class Page
{
    public int Id { get; set; }
    public string Name { get; set; }
    public DateTime Created { get; set; }
}
USE [Play]
GO

/****** Object:  Table [dbo].[t_Pages]    Script Date: 11/28/2012 20:49:34 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[t_Pages](
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [Name] [nvarchar](50) NOT NULL,
    [Created] [datetime] NULL,
 CONSTRAINT [PK_t_Page] PRIMARY KEY CLUSTERED 
(
    [Id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO