尝试使用ASP.NET将数据写入数据库 - 错误“必须声明标量变量”并且不确定原因

时间:2014-04-08 14:03:57

标签: c# asp.net razor webmatrix

我是新手用户,这是我第一次使用这个系统。刚刚尝试做一个非常简单的功能,包括将数据输入表单,按下提交按钮,然后将值存储在我的数据库中。任何人都可以看到我错在哪里?我收到了错误

  

必须声明标量变量@forename

@{


// Initialize variables
var forename = "";
var surname = "";
var email = "";
var street = "";
var gender = "";
var towncity = "";
var postcode = "";
var cardno = "";
var expiry = "";
var securecode = "";
var password = "";

// If this is a POST request validate and process data
if (IsPost) {
    forename = Request.Form["forename"];
    surname = Request.Form["surname"];
    gender = Request.Form["gender"];
    street = Request.Form["street"];
    towncity = Request.Form["townCity"];
    postcode = Request.Form["postcode"];
    cardno = Request.Form["cardno"];
    expiry = Request.Form["expiry"];
    securecode = Request.Form["securecode"];
    password = Request.Form["password"];
    email = Request.Form["email"];

    var db = Database.Open("calcinema");
    var cmd = "INSERT INTO Account (Forename, Surname, Email, Street, Gender, TownCity, Postcode, Cardnumber, Expiry, SecureCode, Password) VALUES (@forename, @surname, @email, @street, @gender, @towncity, @postcode, @cardno, @expiry, @securecode, @password)";
    db.Execute(cmd, forename, surname, email, street, gender, towncity, postcode, cardno, expiry, securecode, password);
    Response.Redirect("~/Browse");

    }
}

最有可能的事情很简单,但是我看不到它,而且我已经按照我所看到的那样遵循相同结构的模板/教程

1 个答案:

答案 0 :(得分:2)

Webmatrix.Database按索引映射查询中的参数,而不是按名称映射。因此,您应该使用@forename,而不是使用@0,依此类推:

var cmd = "INSERT INTO Account (Forename, Surname, Email, Street, Gender, TownCity, Postcode, Cardnumber, Expiry, SecureCode, Password) VALUES (@0, @1, @2, @3, ...)";

代码的其他部分不应更改。可能不是一个好方法,但WebMatrix没有提供其他选择。