asp.net mvc代码一:如何上传图片然后提交"创建"以同样的形式出现
本文关键字:quot 创建 提交 然后 代码 mvc net asp | 更新日期: 2023-09-27 18:02:36
我想使用上传操作上传图像,然后想在同一表单中使用创建操作提交表单。但是当我上传图像时,我不能使用创建按钮创建表单。我想上传图像,然后要创建使用创建按钮的形式。如何使用相同的表单?
这是我的图像模型:
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; }
}
这是我的图像控制器
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);
}
}
这是我的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>
这是我的列表视图:
@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>
看看这个"File Uploads in ASP. ". NET MVC与视图模型"。
似乎他正在做你想要完成的事情。
在HTML中,必须将提交按钮与要提交的表单关联起来。一旦点击"提交"类型的按钮,整个页面就会发送回来(不管你有多少表单)。似乎您想使用JSON POST函数将图像发送到服务器,而不需要发回。然后,一旦有了图像,让用户提交Create表单。
为了解决这个问题,你需要修复文件图像提交按钮,给它一个ID,例如,"createBtn",并改变type="button"。也给文件上传器一个ID,例如"fileUploader"。
用JQUERY中的JSON POST函数为它连接一个按钮点击事件:
$('#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'); }
});
});
然后,你可以做你的花哨的ActionResult,并检查IsAjaxRequest,或做以下操作:
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);
}
我希望这对你有帮助。它不是完整的,但它应该让您为成功做好准备。
在这里我找到了使用HttpPostedFileBase和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");
}