2012-03-16 2 views
-2

Я разрабатываю приложение в asp.net mvc, в котором хочу загрузить файл, и я использовал rendercontrol для рендеринга загрузчика файлов. В связи я использую следующий кодЗагрузка файла в asp.net MVC 2.0

<%: Html.RenderControl(new ControlInfo() 
                   { 
                    ControlID = item.ProjAttID, 
                    DefaultValue = item.DefaultValue, 
                    CanNull = item.CanNull, 
                    // This field can be null. So, if field is null then don't pick the value of expression 
                    // from Regular Expression table. 
                    RegularExpression = (item.RegularExpression != null)? item.RegularExpression1.Value: null, 
                    ErrorMessage = (item.RegularExpression != null) ? item.RegularExpression1.Error : "", 
                    Type = (ControlType)item.FieldType, 
                    Value = (TempData["__" + item.ProjAttID] != null)? TempData["__" + item.ProjAttID].ToString() : null, 
                    ControlAttName = item.ProjAttName, 
                    RegExpressionID = (item.RegularExpression != null) ? item.RegularExpression1.ExpressionID : -1 
                   }, true 
                  ) 
            %> 

и в моем контроллере я использую следующий код, чтобы сохранить файл

int i = new Random().Next(); 
      string fileName = i + Path.GetFileName(data[3]); 

      fileName = fileName.Replace(" ", "-"); 

      string trailingPath = Path.GetFileName(fileName); 
      string fullPath = Path.Combine(Server.MapPath("~/UploadedImages/"), trailingPath); 
      ____.SaveAs(fullPath); 

Я получаю имя файла, но теперь я не могу понять, как Я могу сохранить этот файл. Какой код я могу написать «_ .SaveAs (fullPath)» в этом пространстве « _», поэтому я могу сохранить файл. Пожалуйста, помогите мне

С уважением

Мой controlrenderhelper

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using UserInterface.Models; 
using System.Web.Mvc; 
using System.Text; 

namespace UserInterface.HtmlHelpers 
{ 
    // This enum defines the control types. 
    public enum ControlType 
    { 
     TextField = 1, 
     Password = 2, 
     TextArea = 3, 
     List = 4, 
     CheckBox = 5, 
     //06-03-2012 
     UploadField = 6 
     // 
    } 

    public static class ControlRenderHelper 
    { 
     public static MvcHtmlString RenderControl(this HtmlHelper html, ControlInfo pControlInfo, bool pSaveInfo, int pListSetID = 1) 
     { 
      string scriptString = ""; 
      MvcHtmlString controlString = MvcHtmlString.Create(""); 
      Dictionary<string, string> attributes = new Dictionary<string, string>(); 
      TagBuilder tag; 

      if (pControlInfo.RegExpressionID == 6) 
      { 
       // Adding jquery code to show datepicker widget 
       scriptString = "<script>$(function() { $('#_" + pControlInfo.ControlID + "').datepicker({ dateFormat: 'dd MM yy' });});</script>"; 
      } 

      switch (pControlInfo.Type) 
      { 
       case ControlType.TextField: 

        tag = new TagBuilder("input"); 

        // Tag attributes. 
        attributes.Add("type", "text"); 
        attributes.Add("id", "_" + pControlInfo.ControlID); 
        attributes.Add("name", "_" + pControlInfo.ControlID); 

        // For client side validation (using Jquery). 
        if (!pControlInfo.CanNull) 
        { 
         attributes.Add("class", "required"); 
        } 

        if (pControlInfo.Value != null) 
        { 
         attributes.Add("value", pControlInfo.Value); 
        } 

        else 
        { 
         attributes.Add("value", pControlInfo.DefaultValue); 
        } 

        tag.MergeAttributes(attributes); 

        // For client side validation. 
        scriptString += GetValidationScript(pControlInfo.ControlID, pControlInfo.RegularExpression, pControlInfo.ErrorMessage); 
        controlString = MvcHtmlString.Create(tag.ToString() + scriptString); 

        break; 

       case ControlType.CheckBox: 

        tag = new TagBuilder("input"); 

        // Tag attributes. 
        attributes.Add("type", "checkbox"); 
        attributes.Add("id", "_" + pControlInfo.ControlID); 
        attributes.Add("name", "_" + pControlInfo.ControlID); 
        attributes.Add("value", "Yes"); 
        if (pControlInfo.Value == "Yes") 
        { 
         attributes.Add("checked", "yes"); 
        } 

        tag.MergeAttributes(attributes); 
        tag.InnerHtml = " " + pControlInfo.ControlAttName; 
        controlString = MvcHtmlString.Create(tag.ToString()); 

        break; 

       case ControlType.TextArea: 

        tag = new TagBuilder("textarea"); 

        // Tag attributes. 
        attributes.Add("rows", "4"); 
        attributes.Add("cols", "40"); 
        attributes.Add("id", "_" + pControlInfo.ControlID); 
        attributes.Add("name", "_" + pControlInfo.ControlID); 

        // For client side validation (using Jquery). 
        if (!pControlInfo.CanNull) 
        { 
         attributes.Add("class", "required"); 
        } 

        tag.MergeAttributes(attributes); 

        if (pControlInfo.Value != null) 
        { 
         tag.InnerHtml = pControlInfo.Value; 
        } 

        else 
        { 
         tag.InnerHtml = pControlInfo.DefaultValue; 
        } 

        scriptString += GetValidationScript(pControlInfo.ControlID, pControlInfo.RegularExpression, pControlInfo.ErrorMessage); 
        controlString = MvcHtmlString.Create(tag.ToString() + scriptString); 

        break; 

       case ControlType.List: 

        tag = new TagBuilder("select"); 
        string[] options = pControlInfo.DefaultValue.Split(';'); 
        string selectedValue = pControlInfo.Value; 
        StringBuilder temp = new StringBuilder(); 

        // Tag attributes. 
        attributes.Add("id", "_" + pControlInfo.ControlID); 
        attributes.Add("name", "_" + pControlInfo.ControlID); 
        attributes.Add("class", "selectSize"); 
        tag.MergeAttributes(attributes); 

        foreach (string val in options) 
        { 
         TagBuilder optionTag = new TagBuilder("option"); 
         optionTag.InnerHtml = val; 

         if (val == selectedValue) 
         { 
          optionTag.MergeAttribute("selected", "selected"); 
         } 

         temp.Append(optionTag.ToString()); 
        } 

        tag.InnerHtml = temp.ToString(); 
        controlString = MvcHtmlString.Create(tag.ToString()); 

        break; 

       case ControlType.Password: 

        tag = new TagBuilder("input"); 

        // Tag attributes. 
        attributes.Add("type", "password"); 
        attributes.Add("id", "_" + pControlInfo.ControlID); 
        attributes.Add("name", "_" + pControlInfo.ControlID); 

        // For client side validation (using Jquery). 
        if (!pControlInfo.CanNull) 
        { 
         attributes.Add("class", "required"); 
        } 

        tag.MergeAttributes(attributes); 

        // For client side validation. 
        scriptString = GetValidationScript(pControlInfo.ControlID, pControlInfo.RegularExpression, pControlInfo.ErrorMessage); 
        controlString = MvcHtmlString.Create(tag.ToString() + scriptString); 

        break; 

       case ControlType.UploadField: 

        tag = new TagBuilder("input"); 

        // Tag attributes. 
        attributes.Add("type", "file"); 
        attributes.Add("id", "_" + pControlInfo.ControlID); 
        attributes.Add("name", "_" + pControlInfo.ControlID); 

        // For client side validation (using Jquery). 
        if (!pControlInfo.CanNull) 
        { 
         attributes.Add("class", "required"); 
        } 

        if (pControlInfo.Value != null) 
        { 
         attributes.Add("value", pControlInfo.Value); 
        } 

        else 
        { 
         attributes.Add("value", pControlInfo.DefaultValue); 
        } 

        tag.MergeAttributes(attributes); 

        // For client side validation. 
        scriptString += GetValidationScript(pControlInfo.ControlID, pControlInfo.RegularExpression, pControlInfo.ErrorMessage); 
        controlString = MvcHtmlString.Create(tag.ToString() + scriptString); 

        break; 
      } 

      if (pSaveInfo) 
      { 
       if (pListSetID == 1) 
       { 
        // Please see the RenderedControlsInfo class to understand the purpose of following code snippet. 
        RenderedControlsInfo.L1ControlsID.Add(pControlInfo.ControlID); 
        RenderedControlsInfo.L1ControlsRegExpression.Add(pControlInfo.RegularExpression); 
        RenderedControlsInfo.L1ControlsCanNullProperty.Add(pControlInfo.CanNull); 
        RenderedControlsInfo.L1ControlsErrorMessage.Add(pControlInfo.ErrorMessage); 
       } 

       else 
       { 
        RenderedControlsInfo.L2ControlsID.Add(pControlInfo.ControlID); 
        RenderedControlsInfo.L2ControlsRegExpression.Add(pControlInfo.RegularExpression); 
        RenderedControlsInfo.L2ControlsCanNullProperty.Add(pControlInfo.CanNull); 
        RenderedControlsInfo.L2ControlsErrorMessage.Add(pControlInfo.ErrorMessage); 
       } 
      } 

      return controlString; 
     } 

     static string GetValidationScript(long pControlID, string pRegExp, string pErrorMessage) 
     { 
      string validationScript = null; 

      if (pRegExp != null) 
      { 
       pRegExp = pRegExp.Replace("/", @"\/"); 
       // For client side validation. 
       validationScript = "<script> $(function() {$.validator.addMethod('_" + pControlID + "', function(value, element) {" + 
             "return this.optional(element) || /" + pRegExp + "/i.test(value); }, '" + pErrorMessage + "');$('#_" + 
             pControlID + "').rules('add', '_" + pControlID + "');});</script>"; 

      } 

      return validationScript; 
     } 
    } 
} 
+0

Откуда этот 'Html.RenderControl'? AFAIK нет такого помощника в стандартном ASP.NET MVC. Также что такое '' ControlInfo''? Наконец, какой контроль загрузки файлов вы используете? –

+0

Я использую свой собственный кодированный элемент управления Render Helender – Snake

+0

Хорошо, и вы ожидаете, что мы ответим на ваш вопрос? Вы написали пользовательский код, который вы не показываете, не объясняете, что он делает, и ничего не рассказываете об этом, и спрашиваете, как использовать? Ты серьезно? –

ответ

0

Вы должны добавить HttpPostedFileBase к вашему действию.

+0

но как? Пожалуйста, дайте мне код. – Snake

+0

Вы спрашиваете, как добавить параметр к методу C#? – SLaks

+0

Да, потому что я пытался использовать HttpPostedFileBase, но мне это не удалось – Snake

1

Попробуйте это в качестве основы, она работает для меня:

[Просмотр]

<% using (Html.BeginForm("Upload", "Home", FormMethod.Post, new { enctype = "multipart/form-data" })) 
    { %> 
    <input type="file" name="file" /> 
    <input type="submit" value="upload" /> 
<% } %> 

[Действия]

public ActionResult Upload() 
{ 
    return View(); 
} 

[HttpPost] 
public ActionResult Upload(HttpPostedFileBase file) 
{ 
    if (file != null) 
    { 
     file.SaveAs(Server.MapPath("~/App_Data/Uploads/" + file.FileName)); 
    } 
    return View(); 
} 

Важно для зрения является то, что потребности формируют для установки enctype в multipart/form-data. В действии параметр должен иметь то же имя, что и в форме.