【问题标题】:asp.net mvc2 save selected fileupload (when ModelState.IsValid = false)asp.net mvc2 保存选定的文件上传(当 ModelState.IsValid = false 时)
【发布时间】:2013-09-13 21:35:13
【问题描述】:

我有一个要在其中创建新用户的视图。此表格应包括新用户的姓名和图片。所以它应该是这样的

<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<Project.Models.UserModel>" %>

<asp:Content ID="aboutTitle" ContentPlaceHolderID="TitleContent" runat="server">
    title
</asp:Content>

<asp:Content ID="aboutContent" ContentPlaceHolderID="MainContent" runat="server">
     <%= Html.ValidationSummary("Error: Missing Values!") %>
     <% using (Html.BeginForm("Create", "User", FormMethod.Post, new { enctype = "multipart/form-data" }))
           {%>
<%= Html.TextBoxFor(m => m.name)%>
<%= Html.TextBoxFor(m => m.uploadFile, new { type = "file" })%>
<input type="submit" value="Create User" />
<% } %>   

</asp:Content>

我的 UserModel 如下所示:

public class UserModel
    {
        [Required]
        public string name { get; set; }

        [Required]
        public HttpPostedFileBase uploadFile { get; set; }
    }

我的控制器如下所示:

[AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Create(UserModel model)
        {
            if (!ModelState.IsValid)
                return View(model);
            ...
        }

因此,如果用户只输入一个名称,他/她会收到一条错误消息。此外,输入的名称仍然在文本框中。我的问题是,如果用户只选择一张图片(无名称),他/她仍然会收到错误消息,但是他在文件浏览器中选择的文件没有保存(所以他/她必须再次选择它)。当我将模型返回到 Create-View 时,有没有什么方法 HttpPostedFileBase uploadFile m.uploadFile, new { type = "文件" })%> ?

【问题讨论】:

    标签: asp.net validation file-upload asp.net-mvc-2 model


    【解决方案1】:

    你的问题的答案是你可以模仿这个功能。为此,您必须先将文件保存在服务器上,然后才能显示您在页面上保存的文件的名称。这给用户一种印象,即当他更正错误时会加载文件。

    出于安全原因,浏览器不允许自动加载甚至临时缓存选择进行缓存的文件。

    希望这会有所帮助。

    【讨论】:

    • 感谢您的回答。好的,我明白了。我会像你说的那样模仿这个功能。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-22
    • 1970-01-01
    • 2011-05-11
    • 1970-01-01
    • 2022-12-18
    相关资源
    最近更新 更多