正在保存System.Web.HttpPostedFileWrapper字符串而不是文件路径名

时间:2013-03-10 01:29:28

标签: c# asp.net asp.net-mvc

以前这很好用,但现在代码没有将路径名保存到SitePlanSiteImage字段。如果我调试一切看起来很好,SitePlanSiteImage包含上传文件的路径名(即〜/ UploadedFiles / 20110210104108SiteImage77.jpg)。但是,在SitePlanSiteImage字段中保存后,字符串值为“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 });                                   
}

1 个答案:

答案 0 :(得分:0)

删除了TryUpdateModel()行及其工作原理。但是必须逐行为每个字段更新指定,即siteLocation.Location = collection [“Location”];等等。因为TryUpdateModel已被取出