【问题标题】:Retrieving Data using QueryString with LINQ使用 QueryString 和 LINQ 检索数据
【发布时间】:2014-12-13 22:00:53
【问题描述】:

如何在 asp.net 中使用 request.querystring。我正在尝试使用 Linq 检索数据,但我不断收到错误消息。请尽快回复我。我还是 asp.net 的新手 后面的代码:

      BlogDBDataContext db = new BlogDBDataContext();

        dynamic q = from b in db.Blogs
                    where b.BlogId = Request.QueryString("BlogId") 
                    select  b;


        lv.DataSource = q;
        lv.DataBind();

这给了我一个错误:不可调用的成员'System.Web.HttpRequest.QueryString'不能像方法一样使用。

后面的代码: 即使我尝试此代码:Request.QueryString["BlogId"]

它仍然给我一个错误:无法将类型'string'隐式转换为'int'

【问题讨论】:

    标签: asp.net


    【解决方案1】:

    QueryStringNameValueCollection,而不是方法 - 您应该使用 [] 运算符来访问成员:

    Request.QueryString["BlogId"]
    

    编辑:只需阅读您问题的其余部分。正如错误消息所示,Request.QueryString["BlogId"] 的值是 string,而不是 int。我假设b.BlogIdint,因此您需要先将string 解析为int

    BlogDBDataContext db = new BlogDBDataContext();
    
    int blogId;
    if (int.TryParse(Request.QueryString["BlogId"], out blogId))
    {
        dynamic q = from b in db.Blogs
                    where b.BlogId == blogId 
                    select b;
    
        lv.DataSource = q;
        lv.DataBind();
    }
    

    【讨论】:

    • 我想我找到了我要找的东西,请查看链接:forums.asp.net/post/4987401.aspx
    • 是的,也可以。我更喜欢使用int.TryParse 而不是int.Parse,因此如果有人提交了错误的请求(例如www.example.com/WebPage.aspx?BlogId=a),您的应用不会抛出异常,但这种情况很少见。
    • 但它仍然在这里抛出一个错误,它说不能隐式地将类型 int 转换为 bool : where b.BlogId = blog
    • 糟糕!我有一个错字 - b.BlogId = blogId 应该是 b.BlogId == blogId。我现在已经确定了答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-04-13
    • 2011-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多