2013-03-10 3 views
0

Это хорошо работает, но теперь код не сохраняет путь к полями SiteImage. Если я отлаживаю все выглядит нормально, а SitePlan и SiteImage содержат пути к загружаемым файлам (т. Е. ~/UploadedFiles/20110210104108SiteImage77.jpg). Но после сохранения в полях SitePlan и SiteImage это строковое значение «System.Web.HttpPostedFileWrapper».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() это работает, только EDIT, что это не так:

[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 });         
} 
+0

Не могли бы вы показать код для 'SaveFile()'? Я предполагаю, что это ваш собственный код. –

+0

Обновление завершено, SaveFile() добавлено, приветствия – John

+0

Пятно, вот оно, идя бананы здесь :-) Bizzarly SiteLocationCreate() РАБОТАЕТ, разместив его для отправки сейчас – John

ответ

0

Удалены TryUpdateModel() линия и его работа. Но нужно было указать строку за строкой для каждого обновления поля, то есть siteLocation.Location = collection ["Location"]; и т. д. Так как TryUpdateModel выведено

+0

Рад, что вы поняли! –

Смежные вопросы