简体   繁体   中英

asp.net mvc code first: How to upload image and then submit “create” form in the same form

I want to upload an image using upload action and then want to submit the form using create action in the same form. But when I upload the image i can not create the form using create button. I want to upload image then want to create the form using create button. How can I do this using the same form?

Here is my Image Model:

    public class Image
{
    [Key]
    public int ImageId { set; get; }
    public int? CategoryId { set; get; }
    public virtual Category Category { set; get; }
    public int? SubCategoryId { set; get; }
    public virtual SubCategory SubCategory { get; set; }
    public int? ModelId { set; get; }
    public virtual Model Model { set; get; }
    public int? ProductId { get; set; }
    public virtual Product Product { get; set; }
    public IEnumerable<HttpPostedFile> ImageFile { get; set; }
    public string Name { get; set; }
    public long Size { get; set; }
    public string Path { get; set; }
}

Here is my Image Controller

 public class ImageController : Controller
{
    private ShoppingDbContext db = new ShoppingDbContext();

    //
    // GET: /Image/

    public ActionResult Index()
    {
        var images = db.Images.Include(i => i.Category).Include(i => i.SubCategory).Include(i => i.Model).Include(i => i.Product);
        return View(images.ToList());
    }

    [HttpPost]
    public ActionResult Upload()
    {
        foreach (string file in Request.Files)
        {
            var postedFile = Request.Files[file];
            postedFile.SaveAs(Server.MapPath("~/UploadedFiles/") + Path.GetFileName(postedFile.FileName));


        }
        return RedirectToAction("Create");
    }
    public ActionResult List()
    {
        var uploadedFiles = new List<Image>();

        var files = Directory.GetFiles(Server.MapPath("~/UploadedFiles"));

        foreach (var file in files)
        {
            var fileInfo = new FileInfo(file);

            var picture = new Image() { Name = Path.GetFileName(file) };
            picture.Size = fileInfo.Length;

            picture.Path = ("~/UploadedFiles/") + Path.GetFileName(file);
            uploadedFiles.Add(picture);
        }

        return View(uploadedFiles);
    }

    public ActionResult CategoryListForImage()
    {
        var categories = db.Categorys.ToList();

        if (HttpContext.Request.IsAjaxRequest())
        {
            return Json(
                    new SelectList(
                        categories,
                        "CategoryId",
                        "Name"
                        ), JsonRequestBehavior.AllowGet
                );
        }

        return View(categories);
    }

    public ActionResult SubCategoryListForImage(int CategoryId)
    {
        var subcategories = from sc in db.SubCategories
                            where sc.CategoryId == CategoryId
                            select sc;

        if (HttpContext.Request.IsAjaxRequest())
        {
            return Json(
                new SelectList(
                    subcategories,
                    "SubCategoryId",
                    "SubCategoryName"
                    ), JsonRequestBehavior.AllowGet
                );
        }
        return View(subcategories);
    }

    public ActionResult ModelListForImage(int SubCategoryId)
    {
        var models = from m in db.Models
                     where m.SubCategoryId == SubCategoryId
                     select m;

        if (HttpContext.Request.IsAjaxRequest())
        {
            return Json(
                new SelectList(
                     models,
                    "ModelId",
                    "ModelName"
                    ), JsonRequestBehavior.AllowGet
                );
        }
        return View(models);
    }

    public ActionResult ProductListForImage(int ModelId)
    {
        var products = from p in db.Products
                       where p.ModelId == ModelId
                       select p;

        if (HttpContext.Request.IsAjaxRequest())
        {
            return Json(
                new SelectList(
                     products,
                    "ProductId",
                    "ProductName"
                    ), JsonRequestBehavior.AllowGet
                );
        }
        return View(products);
    }

    //
    // GET: /Image/Details/5

    public ActionResult Details(int id = 0)
    {
        Image image = db.Images.Find(id);
        if (image == null)
        {
            return HttpNotFound();
        }
        return View(image);
    }

    //
    // GET: /Image/Create

    public ActionResult Create()
    {
        ViewBag.CategoryId = new SelectList(db.Categorys, "CategoryId", "Name");
        ViewBag.SubCategoryId = new SelectList(db.SubCategories, "SubCategoryId", "SubCategoryName");
        ViewBag.ModelId = new SelectList(db.Models, "ModelId", "ModelName");
        ViewBag.ProductId = new SelectList(db.Products, "ProductId", "ProductName");
        return View();
    }

    //
    // POST: /Image/Create

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create(Image image)
    {
        if (ModelState.IsValid)
        {
            db.Images.Add(image);
            db.SaveChanges();
            return RedirectToAction("List");
        }

        ViewBag.CategoryId = new SelectList(db.Categorys, "CategoryId", "Name", image.CategoryId);
        ViewBag.SubCategoryId = new SelectList(db.SubCategories, "SubCategoryId", "SubCategoryName", image.SubCategoryId);
        ViewBag.ModelId = new SelectList(db.Models, "ModelId", "ModelName", image.ModelId);
        ViewBag.ProductId = new SelectList(db.Products, "ProductId", "ProductName", image.ProductId);
        return View(image);
    }

    //
    // GET: /Image/Edit/5

    public ActionResult Edit(int id = 0)
    {
        Image image = db.Images.Find(id);
        if (image == null)
        {
            return HttpNotFound();
        }
        ViewBag.CategoryId = new SelectList(db.Categorys, "CategoryId", "Name", image.CategoryId);
        ViewBag.SubCategoryId = new SelectList(db.SubCategories, "SubCategoryId", "SubCategoryName", image.SubCategoryId);
        ViewBag.ModelId = new SelectList(db.Models, "ModelId", "ModelName", image.ModelId);
        ViewBag.ProductId = new SelectList(db.Products, "ProductId", "ProductName", image.ProductId);
        return View(image);
    }

    //
    // POST: /Image/Edit/5

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Edit(Image image)
    {
        if (ModelState.IsValid)
        {
            db.Entry(image).State = EntityState.Modified;
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        ViewBag.CategoryId = new SelectList(db.Categorys, "CategoryId", "Name", image.CategoryId);
        ViewBag.SubCategoryId = new SelectList(db.SubCategories, "SubCategoryId", "SubCategoryName", image.SubCategoryId);
        ViewBag.ModelId = new SelectList(db.Models, "ModelId", "ModelName", image.ModelId);
        ViewBag.ProductId = new SelectList(db.Products, "ProductId", "ProductName", image.ProductId);
        return View(image);
    }

    //
    // GET: /Image/Delete/5

    public ActionResult Delete(int id = 0)
    {
        Image image = db.Images.Find(id);
        if (image == null)
        {
            return HttpNotFound();
        }
        return View(image);
    }

    //
    // POST: /Image/Delete/5

    [HttpPost, ActionName("Delete")]
    [ValidateAntiForgeryToken]
    public ActionResult DeleteConfirmed(int id)
    {
        Image image = db.Images.Find(id);
        db.Images.Remove(image);
        db.SaveChanges();
        return RedirectToAction("Index");
    }

    protected override void Dispose(bool disposing)
    {
        db.Dispose();
        base.Dispose(disposing);
    }
}

Here is my Create View:

@model Online_Shopping_Management.Models.Image

@{
ViewBag.Title = "Create";
}

@section scripts
{
<script type="text/javascript">
    $(function () {
        $.getJSON("/Image/Categories/List/", function (data) {
            var items = "<option> Show Category List </option>";
            $.each(data, function (i, categories) {
                items += "<option value='" + categories.Value + "'>" + categories.Text + "</option>";
            });
            $("#CategoryId").html(items);
        });

        $("#CategoryId").change(function () {
            $.getJSON("/Image/SubCategories/List/" + $("#CategoryId > option:selected").attr("value"), function (data) {
                var items = "<option> Show SubCategory List </option>";
                $.each(data, function (i, subcategory) {
                    items += "<option value='" + subcategory.Value + "'>" + subcategory.Text + "</option>";
                });
                $("#SubCategoryId").html(items);
            });
        });

        $("#SubCategoryId").change(function () {
            $.getJSON("/Image/Models/List/" + $("#SubCategoryId > option:selected").attr("value"), function (data) {
                var items = "<option> Show Models List </option>";
                $.each(data, function (i, model) {
                    items += "<option value='" + model.Value + "'>" + model.Text + "</option>";
                });
                $("#ModelId").html(items);
            });
        });

        $("#ModelId").change(function () {
            $.getJSON("/Image/Products/List/" + $("#ModelId > option:selected").attr("value"), function (data) {
                var items = "<option> Show Products List </option>";
                $.each(data, function (i, product) {
                    items += "<option value='" + product.Value + "'>" + product.Text + "</option>";
                });
                $("#ProductId").html(items);
            });
        });
    });
</script>
}

<h2>Create</h2>

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

<fieldset>
    <legend>Image</legend>

    <div>
        Select a file: <input type="file" name="fileUpload" />

        <input type="submit" value="Upload" />

    </div>

    <label for="CategoryId">Categories</label>
    <select id="CategoryId" name="CategoryId"></select>
    <br /><br />
    <label for="SubCategoryId">SubCategories</label>
    <select id="SubCategoryId" name="SubCategoryId"></select>
    <br /><br />
    <label for="ModelId">Model</label>
    <select id="ModelId" name="ModelId"></select>
    <br /><br />
    <label for="ProductId">Product</label>
    <select id="ProductId" name="ProductId"></select>
    <br/><br/>




    <p>
        <input type="submit" value="Create" />
    </p>
</fieldset>
}

<div>
@Html.ActionLink("Back to List", "Index")
</div>

Here is my List View:

@model IEnumerable<Online_Shopping_Management.Models.Image>

@{
ViewBag.Title = "List";
}

<h2>List</h2>

<p>
@Html.ActionLink("Create New", "Create")
</p>
<table>
 <tr>
    <th>
        @Html.DisplayNameFor(model => model.CategoryId)
    </th>
    <th>
        @Html.DisplayNameFor(model => model.SubCategoryId)
    </th>
    <th>
        @Html.DisplayNameFor(model => model.ModelId)
    </th>
    <th>
        @Html.DisplayNameFor(model => model.Name)
    </th>
    <th>
        @Html.DisplayNameFor(model => model.Size)
    </th>
    <th>
        @Html.DisplayNameFor(model => model.Path)
    </th>
    <th></th>
 </tr>

@foreach (var item in Model) {
 <tr>
    <td>
        @Html.DisplayFor(modelItem => item.Category.Name)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.SubCategory.SubCategoryName)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.Model.ModelName)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.Name)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.Size)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.Path)
    </td>
    <td>
        <img src="@Url.Content(item.Path)" alt="Image" width="100" height="100" />
    </td>
    <td>
        @Html.ActionLink("Edit", "Edit", new { id=item.ImageId }) |
        @Html.ActionLink("Details", "Details", new { id=item.ImageId }) |
        @Html.ActionLink("Delete", "Delete", new { id=item.ImageId })
    </td>
 </tr>
}

</table>

Have a look at this " File Uploads in ASP.NET MVC with View Models " .

Seems like he is doing exactly what you are trying to accomplish.

In HTML, you have to associate a submit button with the form that's being submitted. Once a button of type 'submit' is clicked, the entire page will post back (no matter how many forms you have). It seems like you want to use JSON POST functions to send your image to the server without a post back. Then, once the image is there, have the user submit the Create form.

In order to fix this, you'd want to fix the file image submit button, give it an ID, for example, "createBtn" and change the type="button". Give the file uploader an ID too, for example, "fileUploader".

Wire up a button click event for it, with a JSON POST function in JQUERY:

$('#createBtn').click(function(){
    var file_data = $("#fileUploader").prop("files")[0];
    var form_data = new FormData();
    form_data.append("file", file_data);       
    $.ajax({
        url: "@Url.Action("Create", "Image")",
        data: form_data,
        type: "post",
        success: function(e){ alert('win'); },
        error: function(e){ alert('fail'); }
    });
});

Then, you can do your fancy ActionResult, and check IsAjaxRequest, or do the following:

public JsonResult Create(FormCollection fc)
{
    // Not sure how to get image from fc, but it should be there,
    // Not sure how to get image from Request.Files collection, but it should be there too.
    // Your other data should also be there, in the FormCollection.
    // Do save my image
    return Json("", JsonRequestBehavior.AllowGet);
}

I hope this helps. It's not complete, but it should get you setup for success.

Here i find the solution using HttpPostedFileBase and Form Collection.

public ActionResult AddImageUpload(IEnumerable<HttpPostedFileBase> files,FormCollection fc )
        {
            ImageUpload IU = new ImageUpload();
            IU.MaterialId = Convert.ToInt32((fc["MaterialId"]).Replace("number:",""));
            IU.CategoryId = Convert.ToInt32((fc["CategoryId"]).Replace("number:", "")); 
            string tr = fc["hdnSub"].ToString();
            string result = null;
            string Message, fileName, actualFileName;
            Message = fileName = actualFileName = string.Empty;
            bool flag = false;
            //HttpPostedFileBase f= IU.ImageP;
            string[] SubAssemblyId = (tr.Split(','));
            int i = 0;
            string databaseid = null;
            for (int j=0 ; j<files.Count(); j++)
            {

                var fileContent = Request.Files[j];
                if (fileContent.FileName != "")
                {
                    databaseid = SubAssemblyId[i];
                    string fn = DateTime.Now.ToShortDateString().Replace("/", "") + DateTime.Now.TimeOfDay.Hours + DateTime.Now.TimeOfDay.Minutes + DateTime.Now.TimeOfDay.Seconds + DateTime.Now.TimeOfDay.Milliseconds + Path.GetExtension(fileContent.FileName);
                    fileName = fn;
                    try
                    {
                        if (fileContent != null && fileContent.ContentLength > 0)
                        {
                            var inputStream = fileContent.InputStream;
                            var path = Path.Combine(Server.MapPath("/Images/Product/"), fn);
                            using (var fileStream = System.IO.File.Create(path))
                            {
                                inputStream.CopyTo(fileStream);
                            }

                        }
 }
                    catch (Exception)
                    {

                    }

                }
                i++;

            }
return RedirectToAction("ImageUpload");
        }

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