简体   繁体   中英

Posting form data and image into two separate tables in db from one form using ASP.NET MVC with Entity Framework

My problem is with file upload and Ajax. I have one form with form fields and upload function. I want user to select image from disc, click upload without redirect, display image below, fill in the forms, click create to save form into one table and image into another. The problem is that both upload and create buttons are submiting and I want upload to wait for the rest of the form. Is Ajax the best solution for this? Here is my code:

View:

@using (Html.BeginForm()) 
    {
        @Html.AntiForgeryToken()

        <div class="form-horizontal">
            <h4>sticenikSlika</h4>
            <hr />
            @Html.ValidationSummary(true, "", new { @class = "text-danger" })
            <div class="form-group">
                @Html.LabelFor(model => model.sticenikId, "sticenikId", htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.DropDownList("sticenikId", null, htmlAttributes: new { @class = "form-control" })
                    @Html.ValidationMessageFor(model => model.sticenikId, "", new { @class = "text-danger" })
                </div>
            </div>

            <div class="form-group">
                @Html.LabelFor(model => model.vrijeme, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.vrijeme, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.vrijeme, "", new { @class = "text-danger" })
                </div>
            </div>

            <div class="form-group">
                <div class="col-md-offset-2 col-md-10">
                    <input type="submit" value="Create" class="btn btn-default" />
                </div>
            </div>

        </div>
    }

    <div class="form-horizontal">
        <div class="form-group">
            @using (Html.BeginForm("FileUpload", "UploadImage", FormMethod.Post,
            new { enctype = "multipart/form-data" }))
            {
            <label for="file" class="control-label col-md-2">Upload Image:</label>
            <div class="col-md-10">
                <span class="btn btn-default btn-file">
                    <input type="file" name="file" id="file" />
                </span>
                <input type="submit" value="Upload" class="submit btn btn-default" id="upload" />
            </div>            
            }
        </div>
    </div>

Controller that posts to the database is default Entity framework stuff.

Controller UploadImage:

public ActionResult FileUpload(HttpPostedFileBase file)
            {
                if (file != null)
                {
                    string pic = System.IO.Path.GetFileName(file.FileName);
                    string path = System.IO.Path.Combine(
                                           Server.MapPath("~/Content/images/profile"), pic);

                    file.SaveAs(path);

                    using (MemoryStream ms = new MemoryStream())
                    {
                        file.InputStream.CopyTo(ms);
                        byte[] array = ms.GetBuffer();

JavaScript:

<script>
            $('#upload').click(function (e) {
                e.preventDefault();

                $.ajax({
                    url: '/UploadImage/FileUpload',
                    // not sure what to do 

                    error: function () {
                        alert('Error');
                    }
                });
            });
</script>

When I click 'upload' it saves the image but not the form and when I click 'create' it saves the form but not the image. How to combine those two?

i cant help you in ajax, but if you would to use c#, in your razor page put just one form which contains the data and the image, your form of course should like this

      @using (Html.BeginForm("--", "--", FormMethod.Post,
        new { enctype = "multipart/form-data" })) 

and your controller:

        public ActionResult FileUpload(HttpPostedFileBase file, YourModel model)
        {
            //here save your model
            if (file != null)
            {
                //save file
            }

        }
@using (Html.BeginForm("FileUploadAndSaveData", "UploadImage", FormMethod.Post,
            new { enctype = "multipart/form-data" })) 
    {
        @Html.AntiForgeryToken()

        <div class="form-horizontal">
            <h4>sticenikSlika</h4>
            <hr />
            @Html.ValidationSummary(true, "", new { @class = "text-danger" })
            <div class="form-group">
                @Html.LabelFor(model => model.sticenikId, "sticenikId", htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.DropDownList("sticenikId", null, htmlAttributes: new { @class = "form-control" })
                    @Html.ValidationMessageFor(model => model.sticenikId, "", new { @class = "text-danger" })
                </div>
            </div>

            <div class="form-group">
                @Html.LabelFor(model => model.vrijeme, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.vrijeme, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.vrijeme, "", new { @class = "text-danger" })
                </div>
            </div>

             <div class="form-group">
            @Html.LabelFor(model => model.vrijeme, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.vrijeme, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.vrijeme, "", new { @class = "text-danger" })
            </div>
        </div>          

    </div>
     <label for="file" class="control-label col-md-2">Upload Image:</label>
        <div class="col-md-10">
            <span class="btn btn-default btn-file">
                <input type="file" name="file" id="file" />
            </span>
            <input type="submit" value="Save" class="submit btn btn-default" id="upload" />
        </div>    
    }

    </div>

Create new Action in UploadImage Controller

public ActionResult FileUploadAndSaveData(HttpPostedFileBase file,Model obj) {

FileUpload(HttpPostedFileBase file);/// function Call  for Save Image
SaveData(obj); //Function Call for Save Data
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM