0
我有一個表單上傳文件,但無法將它與其他元素同時保存在同一模型或兩個單獨的模型中。我明白我的第一個問題是我不能嵌套表格,例如如何與其他數據同時上傳文件
@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.有沒有辦法以一種形式做到這一點? (在一個單一的!)。
我將如何實現這一目標?我目前的工作情況如下。
查看:
@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");
}