Search code examples
validationwebmatrix

Expected a "{" but found a "(". Block statements must be enclosed in "{" and "}"


While trying to validate my forms i get the following error: Expected a "{" but found a "(". Block statements must be enclosed in "{" and "}". You cannot use single-statement control-flow statements in CSHTML pages. My lines of code for this page are:

@{
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>

The error page says that the error is with line 18 which suggests there is something wrong with: if (file.IsEmpty()){


Solution

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

    should be:

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

    the if is missing!