【问题标题】:Upload file along with text in Create view在创建视图中上传文件和文本
【发布时间】:2012-03-09 17:23:50
【问题描述】:

我的第一个 .Net/MVC 项目,我生成了一个视图,允许我在数据库中列出、编辑和创建项目,我想在创建页面添加一个文件上传控件,只上传一个文件.

我知道在 [HttpPost] 中我需要“public ActionResult Index(HttpPostedFileBase file)”,但我当前的 [HttpPost] 是这样的:“public ActionResult Create(lm_pics lm_pics)”。

【问题讨论】:

  • 您能展示一下您当前的视图是什么样的吗?

标签: asp.net-mvc


【解决方案1】:

为什么你有 2 个文件输入?为什么你有2个表格?第一种形式还不够吗(当然假设您添加了enctype="multipart/form-data" 属性,因为没有它就无法上传文件)?:

@model PictureUploader_MVC.Models.lm_pics
@{
    ViewBag.Title = "Create";
}
<h2>Upload Picture</h2>

@using (Html.BeginForm(null, null, FormMethod.Post, new { enctype = "multipart/form-data" })) 
{
    @Html.ValidationSummary(true)
    <fieldset>
        <legend>lmit_pics</legend>
        <div class="editor-label">
            @Html.LabelFor(model => model.brand)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.brand)
            @Html.ValidationMessageFor(model => model.brand)
        </div>
        <div class="editor-label">
            @Html.LabelFor(model => model.enabled)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.enabled)
            @Html.ValidationMessageFor(model => model.enabled)
        </div>
        <div>
            <label for="file">Filename:</label>
            <input type="file" name="file" id="file" />
        </div>
    </fieldset>

    <button type="submit">Create</button>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

以及您将处理表单提交的控制器操作:

[HttpPost]
public ActionResult Create(lm_pics lm_pics, HttpPostedFileBase file)
{
    ...    
}

【讨论】:

  • 我不小心发布了带有两个文件输入的代码——我尝试了很多东西。特别是我被上面的链接所迷惑,该链接说将文件输入另一种形式。我将编辑我上面的帖子以删除任何错误信息。
  • 完全有效!我不知道可以将多个参数传递给 Create。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-02-25
  • 1970-01-01
  • 2014-01-06
  • 2023-04-09
  • 1970-01-01
  • 1970-01-01
  • 2023-03-18
相关资源
最近更新 更多