【发布时间】:2016-05-09 10:26:36
【问题描述】:
我将在 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; }
在上传照片和回复my previous question 的 sn-ps 中,上传照片似乎被视为一项单独的任务。即我需要一个单独的表单和控制器来上传照片 (like first part of this answer)。
我想知道有什么方法可以让我以一种形式创建整个用户配置文件并将其照片传递给同一个控制器(其中包括UserProfileViewModel 中的照片)?
我需要注意我不知道使用 jQuery 或 AJAX,我想使用标准的 HTML 助手来完成这项任务。
更新:我的视图如下所示:
@model ProjectManager.Models.UserProfileViewModel
@{
ViewBag.Title = "Create";
}
<h2>@ViewBag.Title</h2>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>User Profile</h4>
<hr />
@Html.ValidationSummary(true)
<div class="form-group">
@Html.LabelFor(model => model.Description, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Description)
@Html.ValidationMessageFor(model => model.Description)
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Name, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Name)
@Html.ValidationMessageFor(model => model.Name)
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Age, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Age)
@Html.ValidationMessageFor(model => model.Age)
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.ImageUrl, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.TextBoxFor(model => model.ImageUrl, new { type = "file" })
@Html.ValidationMessageFor(model => model.ImageUrl)
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="ثبت" class="btn btn-default" />
</div>
</div>
</div>
}
<div class="rtl text-right">
@Html.ActionLink("Back To List", "Index")
</div>
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
【问题讨论】:
-
你的视图部分是什么样子的
-
那你有什么问题?
-
@StephenMuecke 当前文件未发布到 ViewModel 并且 httppost 上的 ImageURL 为空。
-
然后显示您的视图 - 您是否在
<form>标记中包含了enctype属性? -
您需要使用
BeginForm()的重载来允许您添加htmlAttributes,并且因为如果您要上传文件需要添加new {enctype = "multipart/form-data" }。 - 例如@using (Html.BeginForm("UserProfileViewModel ", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
标签: c# asp.net asp.net-mvc asp.net-mvc-4