我有一个图像上传器编辑器模板,该模板当前强类型化为MultiImageUploader视图模型。问题是我有一些自定义数据验证属性,我想在直接调用编辑器模板的视图模型中使用这些属性,而不是通过 MultiImageUploader 视图模型进行路由。
与其使用预设的验证属性调用 MultiImageUploader 视图模型,我想做这样的事情:
public class CreateBrandViewModel
{
.....<snipped>.....
[PermittedFileExtensions("jpg, jpeg, png, gif")]
[MaxFileSize("2MB")]
[UIHint("MultiImageUploader")]
public HttpPostedFileBase Image { get; set; }
//Currently this view model looks like this:
//public MultiImageUploader Image { get; set; } <-- seperate view model
}
我目前无法使用我的首选方式,因为我的编辑器模板没有针对 CreateBrandViewModel 进行强类型化。有没有办法将调用视图模型的@model传递到编辑器模板视图中?:
@model // Here? //
<div class="editor-field">
@Html.TextBoxFor(x => x.Image, new { type = "file" })
@Html.ValidationMessageFor(x => x.Image)
</div>
编辑 1
只是为了澄清,我想这样做的原因是我想从图像上传器更改为通用文件上传器 - 这将需要不同的视图模型上的不同验证属性。为此,目前我需要为每个略有不同的验证参数变体创建一个不同的视图模型和编辑器模板。
编辑2:关于阿瑟顿@Joel答案
我在尝试实现这一点时遇到了一些问题(或者我只是理解不正确)。
我已经创建了接口和抽象类。我的 CreateBrandViewModel 现在继承自 FileUpload。文件上传当前为空,没有共享属性。当我尝试模型时。GetType()。名称 我收到"对象引用未设置为对象的实例"错误。代码如下:
控制器将 CreateBrandViewModel 传递给视图:
[HttpGet]
public ActionResult Create()
{
var model = new CreateBrandViewModel();
model.IsActive = true;
return View(model);
}
然后,"创建"视图调用编辑器模板:
@model CumbriaMD.Infrastructure.ViewModels.BrandViewModels.CreateBrandViewModel
@Html.EditorFor(model => model.File, "EditorTemplates/MultiImageUploader")
然后,模板(出于简单目的)如下所示:
@model CumbriaMD.Infrastructure.ViewModels.FileUploadViewModels.FileUpload
@{
var partialView = Model.GetType().Name;
}
<h1>@partialView</h1>
任何想法将不胜感激:)
我处理这个问题的方法是拥有一个接口,所有允许上传的模型都将实现该接口。如果你实际上有共同的功能,我也会把它与一个具有任何共同属性、属性等的抽象模型结合起来。然后,每个单独的模型将继承抽象类(或者如果您不使用类,则实现接口),然后您可以将其用作@model语句。然后,您可以简单地将任何一次性部分拆分为可以做自己事情的部分视图。
public interface IFileUploadModel
{
// any common properties would go here
}
public abstract class FileUploadModel : IFileUploadModel
{
// implement the common stuff
}
public class CreateBrandViewModel : FileUploadModel
{
[PermittedFileExtensions("jpg, jpeg, png, gif")]
[MaxFileSize("2MB")]
[UIHint("MultiImageUploader")]
public HttpPostedFileBase Image { get; set; }
}
public class SomeOtherUploadModel : FileUploadModel
{
// Other special stuff here
}
然后在您的模板中。
@model FileUploadModel
@{
// Common output code that they all do
// Then the special stuff
if (model.GetType().Name == "CreateBrandViewModel")
{
// Render the partial and pass it the model
Html.RenderPartial("CreateBrandPartialView", Model);
}
}
如果你的类看起来像这样:
public class CreateBrandViewModel
{
[PermittedFileExtensions("jpg, jpeg, png, gif")]
[MaxFileSize("2MB")]
[UIHint("MultiImageUploader")]
public HttpPostedFileBase Image { get; set; }
}
你有一个名为MultiImageUploader.cshtml的EditorTemplate,那么它看起来像:
@model HttpPostedFileBase
@Html.LabelFor(m => m)
@Html.TextBoxFor(x => x, new { type = "file" })
@Html.ValidationMessageFor(x => x)
您将在整体视图中通过以下方式呈现它:
@Html.EditorFor(m => m.Image)