Загрузка с сильно типизированным представлением - проблема - PullRequest
0 голосов
/ 08 ноября 2010

У меня проблема с загрузкой со строго типизированным представлением в ASP.NET MVC.Значение input (view) становится нулевым для представления.Мой код следующий:

<% Html.EnableClientValidation(); %>
<% using (Html.BeginForm("Create", "DownloadsSub", FormMethod.Post, new { enctype = "multipart/form-data" }))
   {%>
    <%: Html.ValidationSummary(true)%>

    <fieldset>
        <legend>Informações do download</legend>

        <div class="editor-label">
            Selecione a categoria do download
        </div>
        <div class="editor-field">
            <%: Html.DropDownList("IDCategoriaDownloads", (IEnumerable<SelectListItem>)ViewData["IDCategoriaDownloads"], "Categorias de downloads...")%>
            <%: Html.ValidationMessageFor(model => model.IDCategoriaDownloads)%>
        </div>

        <div class="editor-label">
            Selecione o formato do arquivo
        </div>
        <div class="editor-field">
            <%= Html.DropDownList("IDFormatoArquivo", (IEnumerable<SelectListItem>)ViewData["IDFormatoArquivo"], "Formatos de arquivos...") %>
            <%: Html.ValidationMessageFor(model => model.IDFormatoArquivo)%>
        </div>

        <div class="editor-label">
            Título do download
        </div>
        <div class="editor-field">
            <%: Html.TextBoxFor(model => model.TituloDownload)%>
            <%: Html.ValidationMessageFor(model => model.TituloDownload)%>
        </div>

        <div class="editor-label">
            Descrição do download
        </div>
        <div class="editor-field">
            <%: Html.TextAreaFor(model => model.DescricaoDownload)%>
            <%: Html.ValidationMessageFor(model => model.DescricaoDownload)%>
        </div>

        <div class="editor-label">
            Data de Postagem
        </div>
        <div class="editor-field">
            <%: Html.TextBoxFor(model => model.DataDownload)%>
            <%: Html.ValidationMessageFor(model => model.DataDownload)%>
        </div>

        <div class="editor-label">
            Selecione o arquivo para download
        </div>
        <div class="editor-field">
            <input type="file" id="txtFile" name="txtFile" />
            <%--<%: Html.TextBoxFor(model => model.CaminhoDownload) %>
            <%: Html.ValidationMessageFor(model => model.CaminhoDownload)%>--%>
        </div>

        <div class="editor-label">
            Quantidade inicial de cliques
        </div>
        <div class="editor-field">
            <%: Html.TextBoxFor(model => model.HitsDownload)%>
            <%: Html.ValidationMessageFor(model => model.HitsDownload)%>
        </div>

        <div class="editor-label">
            Qual o tamanho do arquivo em bytes?
        </div>
        <div class="editor-field">
            <%: Html.TextBoxFor(model => model.TamanhoDownload) %>
            <%: Html.ValidationMessageFor(model => model.TamanhoDownload) %>
        </div>

        <div class="editor-label">
            Possui direitos autorais?
        </div>
        <div class="editor-field">
            <%= Html.DropDownList("StatusDireitosAutorais", (IEnumerable<SelectListItem>)ViewData["StatusDireitosAutorais"], "Selecione...")%>
            <%: Html.ValidationMessageFor(model => model.StatusDireitosAutorais)%>
        </div>

        <div class="editor-label">
            Direitos autorais (preencha apenas se houver)
        </div>
        <div class="editor-field">
            <%: Html.TextBoxFor(model => model.CreditosDownload)%>
            <%: Html.ValidationMessageFor(model => model.CreditosDownload)%>
        </div>

        <p>
            <input type="submit" value="Salvar" />
        </p>
    </fieldset>

<% } %>

И контроллер

[HttpPost]
    public ActionResult Create(tbDownloads _novoDownload, HttpPostedFileBase arquivoUp)
    {
        //var arquivoUp = this.Request.Files[0];
        string nomeArquivoSalvo = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "FilesUpload", "Downloads");
        nomeArquivoSalvo = Path.Combine(nomeArquivoSalvo, Path.GetFileName(arquivoUp.FileName));
        arquivoUp.SaveAs(Server.MapPath("~/FilesUpload/Downloads/") + nomeArquivoSalvo);
        _novoDownload.CaminhoDownload = nomeArquivoSalvo.ToString();

        if (ModelState.IsValid)
        {
            modelo.AddTotbDownloads(_novoDownload);
            modelo.SaveChanges();

            return RedirectToAction("Sucesso", "Mensagens");
        }

        return View(_novoDownload);
    }

Идеи?

Спасибо за помощь!

1 Ответ

1 голос
/ 08 ноября 2010

Имя свойства HttpPostedFileBase должно совпадать с именем поля ввода в представлении.

В представлении вы назвали его "txtFile":

<div class="editor-field">
  <input type="file" id="txtFile" name="txtFile" />
  <%--<%: Html.TextBoxFor(model => model.CaminhoDownload) %>
  <%: Html.ValidationMessageFor(model => model.CaminhoDownload)%>--%>
</div>

Но в контроллере вы называете это:

[HttpPost]
public ActionResult Create(tbDownloads _novoDownload,
                           HttpPostedFileBase arquivoUp)
{ [...] }

Если вы измените это на:

[HttpPost]
public ActionResult Create(tbDownloads _novoDownload,
                           HttpPostedFileBase txtFile)
{ [...] }

Все должно работать.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...