Вопрос

i have a View where i want to create a new User. This form should include the name of the new user and a picture. So it should look like this

<%@ 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>

My UserModel looks like this:

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

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

My Controller looks like this:

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

So if the user only enters a name he/she gets an error message. Also the name which was entered still is in the textbox. My problem is, that if the user only selects a picture (no name) he/she still gets an error, but he the file which he selected in the filebrowser was not saved (so he/she must select it again). Is there any way that when i return my model back to the Create-View the HttpPostedFileBase uploadFile is assumed by <%= Html.TextBoxFor(m => m.uploadFile, new { type = "file" })%> ?

Это было полезно?

Решение

The answer to you question is that you can imitate this functionality. For that you will have to first save the file on the server then you can display the name of the file that you saved on the page. This gives user an impression that the file would be loaded when he corrects the errors.

for security reasons the browser does not allow automatic loading or even temporary caching of the file selected for caching.

Hope this helps.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top