c# - 创建用于上传图像的 ViewModel 的正确方法是什么?

标签 c# asp.net-mvc-4

我的 View 模型如下所示:

public class UploadImageForm
{
    public string Name { get; set; }
    public HttpPostedFileBase Image { get; set; }
}

但它呈现为:

<img src="http://i.imgur.com/E4sRP.png" />

.cshtml看起来像这样:

@using (Html.BeginForm()) {
    @Html.ValidationSummary(true)

    <fieldset>
        <legend>ImageMeta</legend>

        <div class="editor-label">
            @Html.LabelFor(model => model.Name)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Name)
            @Html.ValidationMessageFor(model => model.Name)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.Image)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Image)
            @Html.ValidationMessageFor(model => model.Image)
        </div>

        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
}

如何让它显示标准 <input type="file">改为上传控件?我不确定如何自定义“编辑器”,或者它是否会正确上传。


发现了这些 Html.IdFor.NameFor通过智能感知的助手。现在我可以:

<input id="@Html.IdFor(m => m.Image)" type="file" name="@Html.NameFor(m => m.Image)"/>

我非常喜欢它,因为它避免了创建映射的魔法字符串。仍在尝试确定是否有用于完整输入的 Html 帮助器,如果没有,如何创建一个。

最佳答案

不太确定是否有用于文件输入(上传)的 razor html 助手。但是您可以使用纯 html 输入语法。

@using (Html.BeginForm("Create", "ImageFile", FormMethod.Post, new {enctype = "multipart/form-data"})) {
    <input type="file" name="file1" id="file1" />
}

编辑 ImageFileController 操作看起来像这样:

[HttpPost]
public ActionResult Create(HttpPostedFileBase file) {

  if (file.ContentLength > 0) {
    string name = Path.GetFileName(file.FileName);

    // HINT: Im uploading to App data folder!
    string path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
    file.SaveAs(path);
  }
  return RedirectToAction("Index");
}

此外,Microsoft.Web.Helpers 命名空间中还有一些 Razor 助手,您可以从 here 中找到它们。 .

关于c# - 创建用于上传图像的 ViewModel 的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12273717/

相关文章:

c# - 正则表达式拆分包含标记的文本

javascript - 如何在javascript中获取带有两个参数的URL?

javascript - 在 kendo ui 网格中上下滚动时取消选中复选框

c# - 如何使用 C# 比较两个列表?

javascript - 服务器端表单数据的数据类型

C# Func<> 委托(delegate)参数转换错误

c# - html 选择列表用 c# 添加值

asp.net-mvc - 看不到来 self 的 SignalR 集线器的跟踪输出

c# - 空对象不能转换为值类型

asp.net-mvc - 无法将类型 'System.Collections.Generic.List<string>' 转换为 'System.Web.Mvc.SelectList'