在创建新模型时上载图像

我将在ASP.Net MVC应用程序中为我的用户创建配置文件。 用户创建控制器是这样的:

[HttpPost] [ValidateAntiForgeryToken] public ActionResult Create(UserProfileViewModel userViewModel) { if (ModelState.IsValid) { .... } return View(userViewModel); } 

此外,每个用户模型都有几个属性,包括一张照片。 一切顺利,直到我想添加一个输入字段来接受照片。

 @Html.TextBoxFor(model => model.ImageUrl, new { type = "file" }) 

我将以下字段添加到UserProfileViewModel

 [Display(Name = "Profile Photo")] public HttpPostedFileBase ImageUrl { get; set; } 

在上传照片的片段和我上一个问题的答案中,似乎上传照片被视为一项单独的任务。 即我需要一个单独的表格和控制器来上传照片( 就像这个答案的第一部分 )。

我想知道是否有任何方法可以在一个表单中创建整个用户配置文件并将其照片传递给同一个控制器(其中包括UserProfileViewModel照片)?

我需要注意我不知道使用jQuery或AJAX,我想使用标准的HTML帮助程序来完成这项任务。

更新:我的视图看起来像这样:

 @model ProjectManager.Models.UserProfileViewModel @{ ViewBag.Title = "Create"; } 

@ViewBag.Title

@using (Html.BeginForm()) { @Html.AntiForgeryToken()

User Profile


@Html.ValidationSummary(true)
@Html.LabelFor(model => model.Description, new { @class = "control-label col-md-2" })
@Html.EditorFor(model => model.Description) @Html.ValidationMessageFor(model => model.Description)
@Html.LabelFor(model => model.Name, new { @class = "control-label col-md-2" })
@Html.EditorFor(model => model.Name) @Html.ValidationMessageFor(model => model.Name)
@Html.LabelFor(model => model.Age, new { @class = "control-label col-md-2" })
@Html.EditorFor(model => model.Age) @Html.ValidationMessageFor(model => model.Age)
@Html.LabelFor(model => model.ImageUrl, new { @class = "control-label col-md-2" })
@Html.TextBoxFor(model => model.ImageUrl, new { type = "file" }) @Html.ValidationMessageFor(model => model.ImageUrl)
}
@Html.ActionLink("Back To List", "Index")
@section Scripts { @Scripts.Render("~/bundles/jqueryval") }

除非表单元素包含enctype = "multipart/form-data"属性,否则不会在请求中发送文件输入。 将视图代码更改为

 @using (Html.BeginForm("Create", "User", FormMethod.Post, new { enctype = "multipart/form-data" })) { .... } 

我所有的,你的问题是I want to know are there any methods that I can create whole user profile in one form and pass its photo to the same controller (which included photo in UserProfileViewModel)?

是。 有可能的。 如果你像Stephen Muecke所说的那样覆盖表单,你应该用viewmodel获取照片。 如果在viewmodel中为null,则还可以从请求中检索文件(照片)。

 [HttpPost] [ValidateAntiForgeryToken] public ActionResult Create(UserProfileViewModel userViewModel) { if (ModelState.IsValid) { HttpPostedFileBase fileUploadObj= Request.Files[0]; //for collection HttpFileCollectionBase fileUploadObj= Request.Files; .... } return View(userViewModel); } 

希望这可以帮助 :)

您需要使用允许添加htmlAttributes的BeginForm(),因为您需要添加新的{enctype =“multipart / form-data”}

 @using (Html.BeginForm("UserProfileViewModel ", "Home", FormMethod.Post, new { enctype = "multipart/form-data" })) 

调节器

 [HttpPost] [ValidateAntiForgeryToken] public ActionResult UserProfileViewModel(UserProfileViewModel userViewModel) { if (ModelState.IsValid) { HttpPostedFileBase fileUpload= Request.Files[0]; //for collection HttpFileCollectionBase fileUpload= Request.Files; .... }