我有一个要在其中创建新用户的视图。此表格应包括新用户的姓名和图片。所以它应该看起来像这样
<%@ 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>
我的用户模型看起来像这样:
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 时,有什么方法可以让<%= Html.TextBoxFor(m => m.uploadFile, new { type = "file" })%>假定HttpPostedFileBase uploadFile?