locked
Register.cshtml include a File Upload into a database RRS feed

  • Question

  • User1975269135 posted

    Hi,

    I want simultaneously with the registration of an account and upload a file.
    The strange thing is that the field PassportContent is filled with binary data, but the fields PassportName and PassportType get along no value.
    All the other fields are working well.

    Hope someone can help me.

    @* Remove this section if you are using bundling *@
    @section Scripts {
         <script src="~/Scripts/jquery.validate.min.js"></script>
         <script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
    }
    
    @{
        Layout = "~/_SiteLayout.cshtml";
        Page.Title = "Register";
    
        var db = Database.Open("BCdecl");
    
        // Initialize general page variables
        var email = "";
        var password = "";
        var confirmPassword = "";
        var FirstName = "";
        var MiddleName = "";
        var LastName = "";
        var Address = "";
        var Postcode = "";
        var City = "";
        var BirthDate = "";
        var IBAN = "";
        var Telephone = "";
        var MainJob = "";
        var BSN = "";
        var Nationality = "";
        // var OVChipCardName = "";
        // var OVChipCardType = "";
        // byte[] OVChipCardContent = "";
        int ContentLength = 0;
        var PassportName = "";
        var PassportType = "";
        var PassportContent = new byte[0];
        // byte[] PassportContent;
        var fileSavePath = "";
        var fileName = "";
       
        var RoleId = 2;                 // standard Invigilator
        var ApprovedBC = "No";
    
        // support info
        var BCC = "support@smidmedia.nl";
    
        // Setup validation
        Validation.Add("email", 
            Validator.Regex(@"^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$", 
            "Invalid format for an email address")
            );
        Validation.RequireField("FirstName", "You must specify an firstname.");
        Validation.RequireField("LastName", "You must specify an lastname.");
        Validation.RequireField("password", "Password cannot be blank.");
        Validation.Add("confirmPassword",
            Validator.EqualsTo("password", "Password and confirmation password do not match."));
        Validation.Add("password",
            Validator.StringLength(
                maxLength: Int32.MaxValue,
                minLength: 6,
                errorMessage: "Password must be at least 6 characters"));
        Validation.RequireField("Address", "The address is required.");
        Validation.RequireField("Postcode", "The postcode is required.");
        Validation.RequireField("City", "The city is required.");
        Validation.RequireField("BirthDate", "The date of birth is required.");
        Validation.Add("IBAN",
            Validator.Required("The IBAN is required."),
            Validator.StringLength(18, 18, "and must be 18 characters long."));
        Validation.RequireField("Telephone", "The telephone is required.");
        Validation.RequireField("MainJob", "The MainJob is required.");
        Validation.Add("BSN",
            Validator.Required("The BSN is required."),
            Validator.StringLength(9, 9, "and must be 9 digits long."));
        Validation.RequireField("Nationality", "The nationality is required.");
        Validation.Add("ContentLength", 
            Validator.StringLength(102400, 0, "Document mag niet groter zijn dan 100 Kb"));
    
       
        // If this is a POST request, validate and process data
        if (IsPost && ModelState.IsValid) {
            AntiForgery.Validate();
            email = Request.Form["email"];
            password = Request.Form["password"];
            FirstName = Request.Form["FirstName"];
            MiddleName = Request.Form["MiddleName"];
            LastName = Request.Form["LastName"];
            confirmPassword = Request.Form["confirmPassword"];
            Address = Request.Form["Address"];
            Postcode = Request.Form["Postcode"];
            City = Request.Form["City"];
            BirthDate = Request.Form["BirthDate"];
            IBAN = Request.Form["IBAN"];
            Telephone = Request.Form["Telephone"];
            MainJob = Request.Form["MainJob"];
            BSN = Request.Form["BSN"];
            Nationality = Request.Form["Nationality"];
            
            // process Passport
                if(Request.Files.Count > 0)
                {
                    var UploadPassport = Request.Files[0];
                    PassportName = "";
                    PassportType = "";
                    PassportContent = new byte[0];
                    // byte[] PassportContent;
                    byte[] NewPassportContent;
    
                    if (Path.GetFileName(UploadPassport.FileName) != String.Empty)
                        {
                            // fileSavePath = "";
                            // fileName = Path.GetFileName(UploadPassport.FileName);
                            PassportName = UploadPassport.FileName;
                            // fileSavePath = Path.Combine(coursesRoot, fileName);
                            // fileSavePath = Path.Combine(fileName);
                            var ContentType = UploadPassport.ContentType;
                            PassportType = UploadPassport.ContentType;
                            ContentLength = UploadPassport.ContentLength;
                            var InputStream = UploadPassport.InputStream;
                            NewPassportContent = new byte[ContentLength];
                            InputStream.Read(NewPassportContent, 0, ContentLength);
                            PassportContent = NewPassportContent;
                        }
                        else
                        {
                           PassportName = "";
                           PassportType = "";
                           PassportContent = new byte[0];
                        }
                }
            
            // if (!ReCaptcha.Validate("PRIVATE_KEY")) {
            //     ModelState.AddError("recaptcha", "Captcha response was not correct");
            // }
    
            // If all information is valid, create a new account
            if (Validation.IsValid()) {
                // Insert a new user into the database
                // var db = Database.Open("BCdecl");
    
                
    
                // Check if user already exists
                var user = db.QuerySingle("SELECT Email FROM UserProfile WHERE LOWER(Email) = LOWER(@0)", email);
                if (user == null) {
                    // Insert email into the profile table
                    // db.Execute("INSERT INTO UserProfile (Email, FirstName, MiddleName, LastName, ApprovedBC, Address, Postcode, City, BirthDate, IBAN, Telephone, MainJob, BSN, Nationality, RoleId, OVChipCardName, OVChipCardType, OVChipCardContent) VALUES (@0, @1, @2, @3, @4, @5, @6, @7, @8, @9, @10, @11, @12, @13, @14, @15, @16, @17)", email, FirstName, MiddleName, LastName, ApprovedBC, Address, Postcode, City, BirthDate, IBAN, Telephone, MainJob, BSN, Nationality, RoleId, OVChipCardName, OVChipCardType, OVChipCardContent);
                    db.Execute("INSERT INTO UserProfile (Email, FirstName, MiddleName, LastName, ApprovedBC, Address, Postcode, City, BirthDate, IBAN, Telephone, MainJob, BSN, Nationality, RoleId, PassportName, PassportType, PassportContent) VALUES (@0, @1, @2, @3, @4, @5, @6, @7, @8, @9, @10, @11, @12, @13, @14, @15, @16, @17)", email, FirstName, MiddleName, LastName, ApprovedBC, Address, Postcode, City, BirthDate, IBAN, Telephone, MainJob, BSN, Nationality, RoleId,PassportName, PassportType, PassportContent);
    
                    // Create and associate a new entry in the membership database.
                    // If successful, continue processing the request
                    try {
                        bool requireEmailConfirmation = !WebMail.SmtpServer.IsEmpty();
                        var token = WebSecurity.CreateAccount(email, password, requireEmailConfirmation);
                        if (requireEmailConfirmation) {
                            var hostUrl = Request.Url.GetComponents(UriComponents.SchemeAndServer, UriFormat.Unescaped);
                            var confirmationUrl = hostUrl + VirtualPathUtility.ToAbsolute("~/Account/Confirm?confirmationCode=" + HttpUtility.UrlEncode(token));
    
                            WebMail.Send(
                                from: WebMail.From,
                                replyTo: WebMail.From,
                                isBodyHtml: true,
                                to: email, 
                                bcc: BCC,
                                subject: "Please confirm your account",
                                body: "Hello " + FirstName + " " + MiddleName + " " + LastName + "," + "<br />" + "<br />" + "Your confirmation code is: " + token + "." + "<br />" + "<br />" + "First step: visit now <a href=\"" + confirmationUrl + "\">" + confirmationUrl + "</a> to activate your account." + "<br />" + "<br />" + "Second step: your account has not been approved by the BC, when this is done you receive a message" + "<br />" + "<br />" + "With regards, " + "<br />" + "Supportteam BC"
                            );
                        }
    
                        if (requireEmailConfirmation) {
                            // Thank the user for registering and let them know an email is on its way
                            Response.Redirect("~/Account/Thanks");
                        } else {
                            // Navigate back to the homepage and exit
                            WebSecurity.Login(email, password);
    
                            Response.Redirect("~/");
                        }
                    } catch (System.Web.Security.MembershipCreateUserException e) {
                        ModelState.AddFormError(e.Message);
                    }
                } else {
                    // User already exists
                    ModelState.AddFormError("Email address is already in use.");
                }
            }
        }
    }
    
    <!DOCTYPE html>
    <!-- Datepicker -->
        <link rel="stylesheet" href="//code.jquery.com/ui/1.11.0/themes/smoothness/jquery-ui.css">
        <script src="//code.jquery.com/jquery-1.10.2.js"></script>
        <script src="//code.jquery.com/ui/1.11.0/jquery-ui.js"></script>
        <script src="~/Scripts/jquery.ui.datepicker-en.js"></script>
        <link rel="stylesheet" href="/resources/demos/style.css">
        <script>
        $(function() {
            $("#datepickerDOB").datepicker({
                dateformat: 'DD-MM-YYYY'
            });
        });
        </script>
    <!-- END Datepicker -->
    <!-- verify BSN -->
    <script>
    function verifyBSN(bsn) {
        var j = bsn.length;
        if (j<8 || j>9 || is_int(bsn) == false) {
            return false;
        }
        var pos = 0;
        var result = 0;
        for (i=j; i>0; i--) {
            result += (i != 1) ? (bsn.charAt(pos) * i) : (bsn.charAt(pos) * i * -1);
            pos++;
        }
        return (result % 11 == 0);
    }
        </script>
    <!-- verify BSN -->
    <hgroup class="title">
        <h1>@Page.Title.</h1>
        <h2>Create a new account, all the fields with * are required !</h2>
    </hgroup>
    
    <form method="post">
        @AntiForgery.GetHtml()
        @* If at least one validation error exists, notify the user *@
        @Html.ValidationSummary("Account creation was unsuccessful. Please correct the errors and try again.", excludeFieldErrors: true, htmlAttributes: null)
    
        <table class="">
                <tbody>
                    <tr>
                        <th>Email:</th>
                        <td>
                            &nbsp; * &nbsp;<input class="" name="email" type="text" value="@email" @Validation.For("email")  />
                            @Html.ValidationMessage("email")
                        </td>
                    </tr>
                    <tr>
                        <th>Password:</th>
                        <td>
                            &nbsp; * &nbsp;<input class="" name="password" type="password" value="@password" @Validation.For("password") />
                            @Html.ValidationMessage("password")
                        </td>
                    </tr>
                    <tr>
                        <th>Confirm Password: &nbsp; </th>
                        <td>
                            &nbsp; * &nbsp;<input class="" name="confirmPassword" type="password" value="@email" @Validation.For("confirmPassword") />
                            @Html.ValidationMessage("confirmPassword")
                        </td>
                    </tr>
                    <tr>
                        <th>First name:</th>
                        <td>
                            &nbsp; * &nbsp;<input class="" name="FirstName" type="text" value="@FirstName" @Validation.For("FirstName") />
                            @Html.ValidationMessage("FirstName")
                        </td>
                    </tr>
                    <tr>
                        <th>Middle name: </th>
                        <td>
                             &nbsp; &nbsp;&nbsp; <input class="" name="MiddleName" type="text" value="@MiddleName" @Validation.For("MiddleName") />
                            @Html.ValidationMessage("MiddleName")
                        </td>
                    </tr>
                    <tr>
                        <th>Last name:</th>
                        <td>
                            &nbsp; * &nbsp;<input class="" name="LastName" type="text" value="@LastName" @Validation.For("LastName") />
                            @Html.ValidationMessage("LastName")
                        </td>
                    </tr>
                    <tr>
                        <th>Address:</th>
                        <td>
                            &nbsp; * &nbsp;<input class="" name="Address" type="text" value="@Address" @Validation.For("Address") />
                            @Html.ValidationMessage("Address")
                        </td>
                    </tr>
                    <tr>
                        <th>Postcode: &nbsp; </th>
                        <td>
                            &nbsp; * &nbsp;<input class="" name="Postcode" type="text" value="@Postcode" @Validation.For("Postcode") />
                            @Html.ValidationMessage("Postcode")
                        </td>
                    </tr>
                    <tr>
                        <th>City:</th>
                        <td>
                            &nbsp; * &nbsp;<input class="" name="City" type="text" value="@City" @Validation.For("City") />
                            @Html.ValidationMessage("City")
                        </td>
                    </tr>
                    <tr>
                        <th>Date of birth:</th>
                        <td>
                            &nbsp; * &nbsp;<input class="" name="BirthDate" type="text" id="datepickerDOB" placeholder="date" value="@BirthDate" @Validation.For("BirthDate") />
                            @Html.ValidationMessage("BirthDate")
                        </td>
                    </tr>
                    <tr>
                        <th>IBAN/Bank No: &nbsp; </th>
                        <td>
                            &nbsp; * &nbsp;<input class="" name="IBAN" type="text" value="@IBAN" @Validation.For("IBAN") />
                            @Html.ValidationMessage("IBAN")
                        </td>
                    </tr>
                    <tr>
                        <th>Telephone:</th>
                        <td>
                            &nbsp; * &nbsp;<input class="" name="Telephone" type="text" value="@Telephone" @Validation.For("Telephone") />
                            @Html.ValidationMessage("Telephone")
                        </td>
                    </tr>
                    <tr>
                        <th>Main job?: &nbsp; </th>
                        <td>
                            &nbsp; * &nbsp;<select name="MainJob" id="MainJob">
                                <option value="@MainJob">@MainJob</option>
                                <option value="No">No</option>
                                <option value="Yes">Yes</option>
                            </select>
                            @Html.ValidationMessage("MainJob")
                        </td>
                    </tr>
                    <tr>
                        <th>BSN No:</th>
                        <td>
                            &nbsp; * &nbsp;<input class="" name="BSN" type="text" id="bsn" value="@BSN" @Validation.For("BSN") />
                            @Html.ValidationMessage("BSN")
                        </td>
                    </tr>
                    <tr>
                        <th>Nationality:</th>
                        <td>
                            &nbsp; * &nbsp;<select name="Nationality" id="Nationality">
                                <option value="@Nationality">@Nationality</option>
                                <option value="Dutch">Dutch</option>
                                <option value="Britsh">Britsh</option>
                            </select>
                            @Html.ValidationMessage("Nationality")
                        </td>
                    </tr>
                    <tr>
                        <th>Passport copy: &nbsp;&nbsp; *</th>
                        <!--<td>@FileUpload.GetHtml(initialNumberOfFiles: 1, allowMoreFilesToBeAdded: false, includeFormTag: false, uploadText: "Add")</td>-->
                        <td>@FileUpload.GetHtml(initialNumberOfFiles: 1, allowMoreFilesToBeAdded: false, includeFormTag: false)</td>
                    </tr>
                    <tr><th><input type="submit" value="Register" class="submit" /></th>
                    </tr>
                    <tr><th>&nbsp</th></tr>
                    
                </tbody>
            </table>
            
    </form>

    Wednesday, January 14, 2015 12:08 PM

Answers

  • User-821857111 posted

    You need to add enctype="multipart/form-data" to your form to enable file uploads:

    <form method="post" enctype="multipart/form-data">
        @AntiForgery.GetHtml()

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, January 15, 2015 3:35 AM

All replies

  • User-821857111 posted

    You need to add enctype="multipart/form-data" to your form to enable file uploads:

    <form method="post" enctype="multipart/form-data">
        @AntiForgery.GetHtml()

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, January 15, 2015 3:35 AM
  • User1975269135 posted

    Thanx Mike,

    Its works.

    Thursday, January 15, 2015 1:09 PM