期望“{”但找到“(”。块语句必须括在“{”和“}”中

时间:2012-04-07 09:12:32

标签: validation webmatrix

在尝试验证表单时,我收到以下错误: 期望一个“{”但是找到一个“(”。块语句必须用“{”和“}”括起来。你不能在CSHTML页面中使用单语句控制流语句。 我在这个页面的代码行是:

@{
var db= Database.Open("Games");
var sqlQ = "SELECT * FROM Games";
var data = db.Query(sqlQ);   
}
@{
    var fileerrorMessage = "";
    var NameerrorMessage = "";
    var Gamefile = "";
    var GameName = "";
    var isValid = true;
    if (IsPost) {
        if (file.IsEmpty()){
        fileerrorMessage = "Please upload a file.";
        isValid = false;
        }

    else (formName.IsEmpty()){
        NameerrorMessage = "Please give the game a name.";
        isValid = false;
    }

    if (isValid){
    var fileData = Request.Files[0];
    var fileName = Path.GetFileName(fileData.FileName);
    var fileSavePath = Server.MapPath("~/upload/" + fileName);
    fileData.SaveAs(fileSavePath);
    GameName=Request["formName"];
    Gamefile=fileName;
    var SQLINSERT = "INSERT INTO Games (Name, file_path) " + "VALUES (@0, @1)";
    db.Execute(SQLINSERT, GameName, Gamefile);
    Response.Redirect("default.cshtml");
    }

    else
    {
        <p class="message error">Please correct the errors and resubmit the form.</P> 
    }

    }
}
<form action="" method="post" enctype="multipart/form-data">

  <input type="file" name="file" id="file" /><p>
    @if(!fileerrorMessage.IsEmpty()) {
        <label for="file" class="validation-error">
            @fileerrorMessage
        </label>
    }
  <p><input type="text" name="formName" value="@GameName" />
     @if(!NameerrorMessage.IsEmpty()) {
        <label for="file" class="validation-error">
            @NameerrorMessage
        </label>
     }

  <input type="submit" value="Add Game" />
</form>

错误页面显示错误与第18行有关,表明存在错误:if (file.IsEmpty()){

2 个答案:

答案 0 :(得分:1)

else (formName.IsEmpty()){
    NameerrorMessage = "Please give the game a name.";
    isValid = false;

应该是:

else if (formName.IsEmpty()){
    NameerrorMessage = "Please give the game a name.";
    isValid = false;

if丢失!

答案 1 :(得分:1)

我在这里遇到了类似的问题 - 对我来说问题是:

@{
    var stuff = getSomeStuff();

    if (stuff.Whatever)
        doThing();
}
@if (stuff.Condition) {
<button/>
} else {
<a href=""></a>
}

问题是没有if语句,即使是像上面这样明显的代码块中的第一个语句,也可以在没有花括号的情况下使用。所以上面变成了:

@{
    var stuff = getSomeStuff();

    if (stuff.Whatever)
    {
        doThing();
    }
}
@if (stuff.Condition) {
<button/>
} else {
<a href=""></a>
}