使用cookie执行 SQL select

Using cookie to execute SQL select

我正在尝试在我的 .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' 语句,除非万不得已。

你的变量 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"