【问题标题】:Using cookie to execute SQL select使用cookie执行SQL select
【发布时间】:2015-06-11 23:06:29
【问题描述】:

我正在尝试在我的 .NET Razor 应用程序中使用 cookie 来记住用户表单字段信息。

用户第一次使用表单提交查询时,会在数据库中插入一个条目,并为该条目创建一个 GUID。然后,此 GUID 将作为 cookie 保存在用户计算机上:

// Create Enquiry Cookie
HttpCookie myCookie = new HttpCookie("BookingReq");
myCookie.Value = bookingguid;
myCookie.Expires = DateTime.Now.AddYears(1);
Response.Cookies.Add(myCookie);

下次用户转到不同的属性页时,我想使用 cookie 中的 GUID 从数据库中提取关于他们上次请求的信息,并使用相同的信息填充表单。

首先我这样做:

if(Request.Cookies["BookingReq"] != null){
    var breq = db.Query("SELECT * FROM BookingRequests WHERE BookingGUID = @0", Request.Cookies["BookingReq"].Value);
}

理论上,这应该可行,但我无法使用传统方法填充表单:

<div class="form-group">
    <label for="customerName">Your Name</label>
        <input type="text" value="@breq.CustomerName" class="form-control" id="customerName" name="customerName">
</div>
<div class="form-group">
    <label for="customerEmail">Email address</label>
        <input class="form-control" value="@breq.CustomerEmail" id="customerEmail" name="customerEmail">
</div>

我猜这是因为您不能从“if”语句中调用变量?我在这里有什么选择?

除非万不得已,否则我不想对每个表单域都执行“if”语句。

【问题讨论】:

  • 请告诉我们“我无法填写表格”的方式。它会让它们空白吗?错误?另外,对于第一个第二个代码块,这是在视图中还是在控制器中?
  • 我实际上是在 asp.net 网页框架上构建的,因此视图和控制器之间没有真正的区别,但问题本质上是视图问题。表单中的 @breq.CustomerEmail 值不是一个选项,因为该变量位于“if”语句中。如果我将它从“if”语句中取出,那么它是一个选项,但随后我将删除逻辑以查看 cookie 是否不存在(这通常是不存在的)。

标签: sql .net razor cookies webmatrix


【解决方案1】:

变量bref 的范围是错误的。您在 if 块中声明它,这是唯一可以使用它的地方。此外,如果 breq 为空,breq.CustomerName 将失败。所以修复会是这样的

var customerName = "";
var customerEmail = "";
if (Request.Cookies["BookingReq"] != null) {
    var breq = db.Query("SELECT * FROM BookingRequests WHERE BookingGUID = @0", Request.Cookies["BookingReq"].Value);
    //I don't know webmatrix so I don't know what happens to breq if that value doesn't exist - I'll assume it's null
    if (breq != null) {
        customerName = breq.CustomerName;
        customerEmail = breq.CustomerEmail;
    }
}

然后在控件中您可以使用value="@customerName" 和value="@customerEmail"

【讨论】:

  • 有道理!给我半个小时,我会付诸行动的;)
  • 感谢您的帮助,非常感谢
猜你喜欢
  • 2011-01-22
  • 2021-03-15
  • 1970-01-01
  • 2018-01-20
  • 1970-01-01
  • 1970-01-01
  • 2015-06-15
  • 2020-08-29
  • 2011-06-02
相关资源
最近更新 更多