2015-04-07 49 views
1

我想在我的.NET Razor應用程序中使用cookie來記住用戶表單字段信息。使用cookie執行SQL select

用戶第一次使用表單提交查詢時,會將一個條目插入到數據庫中,併爲該條目創建一個GUID。然後,該GUID被保存爲用戶計算機上的cookie:

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

下一次用戶進入到一個不同的屬性頁,我想使用GUID在Cookie中提取信息有關數據庫的自己最後的請求,並用相同的信息填充表單。

首先我這樣做:

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'語句,除非它絕對是最後的手段嗎?

謝謝,加文

+0

請讓我們知道以什麼方式「我不能夠填充表單」。它會讓它們變成空白嗎?錯誤?此外,對於第一個第二塊代碼,這是在視圖還是控制器? –

+0

我實際上是在asp.net網頁框架上構建它,所以視圖和控制器之間沒有真正的區別,但問題本質上是視圖問題。表單中的@ breq.CustomerEmail值不是一個選項,因爲該變量位於'if'語句中。如果我將它從'if'語句中取出,那麼它是一個選項,但是我將刪除邏輯以查看cookie是否不存在(通常不是這種情況)。 – Gavin5511

回答

2

你變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"

+0

是有道理的!給我半小時,我會付諸行動;) – Gavin5511

+0

感謝您的幫助,非常感謝 – Gavin5511