これは以前は正常に機能していましたが、現在、コードはパス名をSitePlan
andSiteImage
フィールドに保存していません。デバッグすると、すべて正常に見えSitePlan
、SiteImage
アップロードされたファイルへのパス名が含まれています (つまり、~/UploadedFiles/20110210104108SiteImage77.jpg)。ただし、フィールドに保存するSitePlan
とSiteImage
、文字列値「System.Web.HttpPostedFileWrapper」になります。
保存がうまくいき、保存されている値を監視およびデバッグするのはパス名であるため、これに苦労しているため、エラーはなく、すべてが機能しているように見えます。データベースにはパスがなく、この文字列「System.Web.HttpPostedFileWrapper」だけです。どんなコメントでも大歓迎です
これが私のコントローラーコードです:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult SiteLocationEdit(int id, FormCollection collection)
{
SiteLocation siteLocation = this._siteRepository.GetSite(Convert.ToInt16(collection["SiteId"])).SiteLocation;
if (Request.Files.Count > 0 && Request.Files["SitePlan"].ContentLength > 0)
{
DeleteFile(siteLocation.SitePlan);
siteLocation.SitePlan = SaveFile(Request.Files["SitePlan"], @"~/UploadedFiles", "SitePlan" + siteLocation.SiteId.ToString());
}
if (Request.Files.Count > 0 && Request.Files["SiteImage"].ContentLength > 0)
{
DeleteFile(siteLocation.SiteImage);
siteLocation.SiteImage = SaveFile(Request.Files["SiteImage"], @"~/UploadedFiles", "SiteImage" + siteLocation.SiteId.ToString());
}
TryUpdateModel(siteLocation);
if (!ModelState.IsValid)
return View(siteLocation);
this._siteRepository.Save(User.Identity.Name);
return RedirectToAction("SiteLocationDetails", new { id = siteLocation.SiteId });
}
部分ビューを含むビューを次に示します (この記事の後半で示します)。
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<Lms.Model.SiteLocation>" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
<%= Html.Encode(Model.Site.SiteDescription) %>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<%=Html.Script("~/Scripts/jquery.textarea-expander.js")%>
<%= Html.ValidationSummary("Location Create was unsuccessful. Please correct the errors and try again.\n If you uploaded images during this update please upload again.")%>
<% using (
Html.BeginForm
(
"SiteLocationEdit",
"Site",
FormMethod.Post,
// add an encoding type attribute
// that is required for file upload
new { enctype = "multipart/form-data" }
)
)
{%>
<% Html.RenderPartial("SiteTabs", Model.Site); %>
<div class="clear">
</div>
<% Html.RenderPartial("SiteLocationForm", Model); %>
<% } %>
<script type="text/javascript">
/* jQuery textarea resizer plugin usage */
$(document).ready(function() {
jQuery("textarea[class*=expand]").TextAreaExpander(); // initialize all expanding textareas, new code, john s 10/08/2010
});
</script>
</asp:Content>
部分的なビューは次のとおりです。
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<Lms.Model.SiteLocation>" %>
<fieldset>
<div>
<h3>
<label id="Label2" style="text-align: left">
<%= "Site Location: " + Html.Encode(Model.Site.SiteDescription) %></label>
</h3>
</div>
<div class="formFields">
<ul>
<%--This is used to identify the site object to update when the model is returned to the controller--%>
<%= Html.Hidden("SiteId", Model.SiteId)%>
<li>
<label for="Latitude">
<strong>Latitude:</strong></label>
<%= Html.TextBox("Latitude")%>
<%= Html.ValidationMessage("Latitude", "*")%>
</li>
<li>
<label for="Longitude">
<strong>Longitude:</strong></label>
<%= Html.TextBox("Longitude") %>
<%= Html.ValidationMessage("Longitude", "*") %>
</li>
<li>
<label for="Location">
<strong>Location Address:</strong></label>
<label><%= Html.TextArea("Location", Model.Location, new { @class = "expand50-200"}) %></label>
<%= Html.ValidationMessage("Location", "*") %>
</li>
<li>
<label for="NearestPostcode">
<strong>Nearest Postcode:</strong></label>
<%= Html.TextBox("NearestPostcode") %>
<%= Html.ValidationMessage("NearestPostcode", "*") %>
</li>
<li>
<label for="TimeFromOfficeToTurbine">
<strong>Office to Windfarm (Time):</strong></label>
<%= Html.TextBox("TimeFromOfficeToTurbine") %>
<%= Html.ValidationMessage("TimeFromOfficeToTurbine", "*") %>
</li>
<li>
<label for="Directions">
<strong>Comments:</strong></label>
<label><%= Html.TextArea("Directions", Model.Directions, new { @class = "expand50-200" })%> </label>
<%= Html.ValidationMessage("Directions", "*") %>
</li>
<li>
<h5><strong>For Image Uploads:</strong> Please use only JPG,JPEG or GIF formats.
Image size should be appropriate for the webpage to display, approximately 500x375 (WidthxHeight)
</h5>
</li>
<li>
<label for="Site Plan">
<strong>Site Plan:</strong></label>
<input id="SitePlan" name="SitePlan" type="file" />
</li>
<li>
<label for="Site Image">
<strong>Site Image:</strong></label>
<%-- <%//= Html.TextBox("SiteImage", Model.SiteImage)%>
<%//= Html.ValidationMessage("SiteImage", "*") %>--%>
<input id="SiteImage" name="SiteImage" type="file" />
</li>
</ul>
</div>
</fieldset>
<div class='demo'>
<%=Html.ActionLink("< Back to List", "Index") %><input type="submit" value="Save" />
</div>
コントローラーコードのファイル保存手順は次のとおりです。
protected String SaveFile(HttpPostedFileBase file, String path, string name)
{
if (file != null && file.ContentLength > 0)
{
if (path == null)
{
throw new ArgumentNullException("path cannot be null");
}
string fileType = file.FileName.Substring(file.FileName.LastIndexOf("."), file.FileName.Length - file.FileName.LastIndexOf("."));
String relpath = String.Format("{0}/{1}", path, PrefixFName(name + fileType));
try
{
file.SaveAs(Server.MapPath(relpath));
return relpath;
}
catch (HttpException e)
{
throw new ApplicationException("Cannot save uploaded file", e);
}
}
return null;
}
これが SiteLocationCreate() です これは機能しますが、そうでない編集だけです:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult SiteLocationCreate(SiteLocation siteLocation, FormCollection collection)
{
// TODO CF: Look into this line. Is there a better way to do it? I would think so.
// It uses a hidden field in the object form
Site site = this._siteRepository.GetSite(Convert.ToInt16(collection["SiteId"]));
site.SiteLocation = siteLocation;
if (Request.Files.Count > 0 && Request.Files["SitePlan"].ContentLength > 0)
{
DeleteFile(siteLocation.SitePlan);
siteLocation.SitePlan = SaveFile(Request.Files["SitePlan"], @"~/UploadedFiles", "SitePlan" + siteLocation.SiteId.ToString());
}
if (Request.Files.Count > 0 && Request.Files["SiteImage"].ContentLength > 0)
{
DeleteFile(siteLocation.SiteImage);
siteLocation.SiteImage = SaveFile(Request.Files["SiteImage"], @"~/UploadedFiles", "SiteImage" + siteLocation.SiteId.ToString());
}
if (!ModelState.IsValid)
return View(siteLocation);
this._siteRepository.Save(User.Identity.Name);
return RedirectToAction("SiteLocationDetails", new { id = site.SiteId });
}