当前位置: 首页 > 编程语言 > C#

创建新模型时上传图像Share

时间:2023-04-11 00:23:13 C#

创建新模型时上传图像我将在ASP.NetMVC应用程序中为我的用户创建配置文件。用户创建控制器如下所示:[HttpPost][ValidateAntiForgeryToken]publicActionResultCreate(UserProfileViewModeluserViewModel){if(ModelState.IsValid){....}returnView(userViewModel);此外,每个用户模型都有几个属性,包括照片。一切都很顺利,直到我想添加一个输入字段来接受照片。@Html.TextBoxFor(model=>model.ImageUrl,new{type="file"})我将以下字段添加到UserProfileViewModel:[Display(Name="ProfilePhoto")]publicHttpPostedFileBaseImageUrl{get;放;从上传照片的片段和我之前问题的答案来看,上传照片似乎被视为一个单独的任务。即我需要一个单独的表单和控制器来上传照片(就像这个答案的第一部分)。我想知道是否有任何方法可以以一种形式创建整个用户配置文件并将他们的照片传递给同一个控制器(包括UserProfileViewModel照片)?我需要注意,我不知道jQuery或AJAX,我想使用标准的HTML助手来完成这项任务。更新:我的视频看起来像这样:@modelProjectManager.Models.UserProfileViewModel@{ViewBag.Title="Create";}@ViewBag.Title@using(Html.BeginForm()){@Html.AntiForgeryToken()用户配置文件@Html.ValidationSummary(true)@Html.LabelFor(model=>model.Description,new{@class="control-标签col-md-2"})@Html.EditorFor(model=>model.Description)@Html.ValidationMessageFor(model=>model.Description)@Html.LabelFor(model=>model.Name,new{@class=“控制标签col-md-2”})@Html.EditorFor(model=>model.Name)@Html.ValidationMessageFor(model=>model.Name)@Html.LabelFor(model=>model.Age,new{@class="control-labelcol-md-2"})@Html.EditorFor(model=>model.Age)@Html.ValidationMessageFor(model=>model.Age)@Html.LabelFor(model=>model.ImageUrl,new{@class="control-labelcol-md-2"})@Html.TextBoxFor(model=>model.ImageUrl,new{type="file"})@Html.ValidationMessageFor(model=>model.ImageUrl)}@Html.ActionLink("BackToList","Index")@sectionScripts{@Scripts.Render("~/bundles/jqueryval")}除非表单元素包含enctype="multipart/form-data”属性,否则请求中不会发送文件输入将视图代码改为@using(Html.BeginForm("Create","User",FormMethod.Post,new{enctype="multipart/form-data"})){....}都是我的,你的问题是我想知道有没有什么方法可以以一种形式创建整个用户配置文件并将其照片传递给同一个控制器(其中包括UserProfileViewModel中的照片)?是的。可能的。如果您像StephenMuecke所说的那样覆盖表单,则应该使用视图模型获取照片。如果视图模型中为null,您还可以从请求中检索文件(照片)。[HttpPost][ValidateAntiForgeryToken]publicActionResultCreate(UserProfileViewModeluserViewModel){if(ModelState.IsValid){HttpPostedFileBasefileUploadObj=Request.Files[0];//用于收集HttpFileCollectionBasefileUploadObj=Request.Files;....}返回视图(userViewModel);希望这会有所帮助:)您需要使用允许添加htmlAttributes的BeginForm(),因为您需要添加新的{enctype="multipart/form-data"}@using(Html.BeginForm("UserProfileViewModel","Home",FormMethod.Post,new{enctype="multipart/form-data"}))Regulator以上是C#学习教程:新建模型时上传图片的全部内容分享,如果对大家有用,需要的话了解更多C#学习教程,希望大家多多关注—[HttpPost][ValidateAntiForgeryToken]publicActionResultUserProfileViewModel(UserProfileViewModeluserViewModel){if(ModelState.IsValid){HttpPostedFileBasefileUpload=Request.Files[0];//用于收集HttpFileCollectionBasefileUpload=Request.Files;....}本文收集自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处: