【发布时间】:2023-03-30 05:40:01
【问题描述】:
我在表单中上传了文件,但我无法将其与其他元素同时保存在同一模型或两个单独的模型中。我知道我的第一个问题是我不能嵌套表单,例如
@using (Html.BeginForm("Create", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<form class="form-horizontal">
<input />
<input />
@using (Html.BeginForm("Create", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<form class="form-horizontal">
<input image upload/>
<input />
</form>
}
</form>
}
所以我现在有两个单独的表单并且可以很好地工作,但我想要一些东西: 1.当用户选择图像上传任何当前输入的不被删除的值时 2.将所有输入数据(所有表单元素)与图像一起更新到所选模型。 3.有没有办法以一种形式做到这一点? (在一个 r 中!)。
我将如何实现这一目标?我目前的工作如下。
查看:
@model client.Models.jobs
@{
ViewBag.Title = "Create Job Details";
}
<br /><br /><br />
@using (Html.BeginForm("Create", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<form class="form-horizontal">
<fieldset>
<legend>Job Details</legend>
<!--Postcode search--><label for="inputEmail" class="col-lg-2 control-label">Job's Name</label>
<input name="jobname" type="text" placeholder="Job Name" /><br /><br />
<label for="jobdescription" class="col-lg-2 control-label">Job Description</label>
<br /><br />
<div class="col-lg-10">
<textarea class="form-control" rows="3" name="textArea" placeholder="Write here..."></textarea>
<span class="help-block">The more details you enter the easier the Tradesmen can work</span>
</div>
<br /><br /><br /><br /><br /><br />
<label for="uploadphotos" class="col-lg-2 control-label">
Add PHOTOS (Optional)
@Html.LabelFor(model => model.ImageData, new { @class = "control-label col-md-2" })
<input name="Image" type="file" />
@Html.ValidationMessageFor(model => model.ImageData)
<button type="submit" value="Upload" onclick="location.href='@Url.Action("Create", "Home")'">Upload</button>
@ViewBag.Message
</label>
<br /><br />
<label for="select" class="col-lg-2 control-label">Tell us which stage you’re at</label>
<div class="col-lg-10">
<select class="form-control" name="stage">
<option>Preplan</option>
<option>already started</option>
<option>Almost finished</option>
<option>Needs redone fully</option>
</select>
</div>
<br /><br /><br /><br />
<label for="select" class="col-lg-2 control-label"> When would you like the job to start?*</label>
<div class="col-lg-10">
<select class="form-control" name="startjob">
<option>ASAP</option>
<option>1-2 weeks</option>
<option>1 month</option>
<option>1+</option>
</select>
</div>
<br /><br /><br /><br />
<label for="select" class="col-lg-2 control-label">What's your approximate budget?</label>
<div class="col-lg-10">
<select class="form-control" name="budget">
<option>£0-500</option>
<option>£500-100</option>
<option>£1000-2000</option>
<option>£2000+</option>
</select>
</div>
<br /><br /><br /><br />
</form>
}
@using (Html.BeginForm("getJobFormValues", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<form class="form-horizontal">
<input name="jobname" type="text" placeholder="Job Name" /><br /><br />
<button type="submit" class="btn btn-success btn-lg">Next</button>
</form>
}
@section Scripts{
<script>
debugger
</script>
}
控制器和动作:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(uploadedfiles pic, HttpPostedFileBase image)
{
if (ModelState.IsValid)
{
if (image != null)
{
//attach the uploaded image to the object before saving to Database
pic.ContentType = Convert.ToString(image.ContentLength);
pic.ImageData = new byte[image.ContentLength];
image.InputStream.Read(pic.ImageData, 0, image.ContentLength);
//Save image to file
var filename = image.FileName;
var filePathOriginal = Server.MapPath("/Content/Uploads/Originals");
var filePathThumbnail = Server.MapPath("/Content/Uploads/Thumbs");
string savedFileName = Path.Combine(filePathOriginal, filename);
image.SaveAs(savedFileName);
//Read image back from file and create thumbnail from it
var imageFile = Path.Combine(Server.MapPath("~/Content/Uploads/Originals"), filename);
using (var srcImage = Image.FromFile(imageFile))
using (var newImage = new Bitmap(100, 100))
using (var graphics = Graphics.FromImage(newImage))
using (var stream = new MemoryStream())
{
graphics.SmoothingMode = SmoothingMode.AntiAlias;
graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
graphics.DrawImage(srcImage, new Rectangle(0, 0, 100, 100));
newImage.Save(stream, ImageFormat.Png);
var thumbNew = File(stream.ToArray(), "image/png");
pic.ImageData = thumbNew.FileContents;
pic.ImageName = filename;
}
}
//Save model object to database
db.uploadedfiles.Add(pic);
ViewBag.Message = "Image Uploaded Successfully!!";
try
{
db.SaveChanges();
}
catch (DbEntityValidationException e)
{
foreach (var eve in e.EntityValidationErrors)
{
Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
eve.Entry.Entity.GetType().Name, eve.Entry.State);
foreach (var ve in eve.ValidationErrors)
{
Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"",
ve.PropertyName, ve.ErrorMessage);
}
}
throw;
}
ViewBag.Message = "Image Uploaded Successfully!!";
return View("JobDetails");
//return RedirectToAction("getJobFormValues");
}
return View("JobDetails");
}
[HttpPost]
public ActionResult getJobFormValues(jobs job)
{
string quoteSearch = Request["quoteSearch"];
string jobname = Request["jobname"];
string jobmessage = Request["textArea"];
string uploadedphoto = Request["uploadphotos"];
string stage = Request["stage"];
string startjob = Request["startjob"];
string budget = Request["budget"];
int imgid = 2;
//Save model object to database
//Save personal details model object to database
if (ModelState.IsValid)
{
//Save model object to database
db.jobs.Add(new jobs
{
name = jobname,
jobmessage = jobmessage,
//iscomplete
//jobbyuserid
//responsibletradesmanid
//jobmessage
stage = stage,
startjob = startjob,
budget = Convert.ToInt32(budget),
ImageId = imgid
//ImageName
//ImageAlt
//ImageData
//ContentType
});
try
{
db.SaveChanges();
}
catch (DbEntityValidationException e)
{
foreach (var eve in e.EntityValidationErrors)
{
Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
eve.Entry.Entity.GetType().Name, eve.Entry.State);
foreach (var ve in eve.ValidationErrors)
{
Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"",
ve.PropertyName, ve.ErrorMessage);
}
}
throw;
}
return RedirectToAction("PersonalDetails", new
{
quoteSearch = quoteSearch,
jobname = jobname,
jobmessage = jobmessage,
uploadedphoto = uploadedphoto,
stage = stage,
startjob = startjob,
budget = budget
});
}//model state
return View("JobDetails");
}
【问题讨论】:
标签: c# entity-framework file-upload asp.net-mvc-5