Required Byte[] on View Model

本文关键字:View Model on Byte Required | 更新日期: 2023-09-27 18:03:30

我有一个视图模型,它有一个Byte[]属性,它是需要在用户创建一个新项目的时刻,这是我的模型:

public class ClassViewModel2
{
        public int ClassId { get; set; }
        [Required(ErrorMessage = "This field is required to create a Class")]
        public string Name { get; set; }
        [Required(ErrorMessage = "This field is required to create a Class")]
        public string Description { get; set; }
        [Required(ErrorMessage = "This field is required to create a Class")]
        public byte[] ThumbNail { get; set; }
        [Required(ErrorMessage = "This field is required to create a Class")]
        public byte[] MainImage { get; set; }
}

但是如果Byte[]是null,它将继续创建项目,它与其他属性一起工作得很好,所以我不确定如何包含对此的验证。

这是我的编辑控制器:

[HttpPost]
        [ValidateInput(false)]
        [Authorize(Roles = Constants.Roles.Admins)]
        public virtual ActionResult Edit(ClassViewModel classdetail, HttpPostedFileBase fmainimage,
                                         HttpPostedFileBase fthumbnail)
        {
            UserProfile up = GetUserProfile();
            if (up != null)
            {
                if (ModelState.IsValid)
                {
                    var mclass =
                        (from c in _db.Classes where c.ClassId == classdetail.ClassId select c).FirstOrDefault() ??
                        new Class();
                    Mapper.Map(classdetail, mclass, typeof(ClassViewModel), typeof(Class));
                    var mclass2 =
                        (from c in _db.Classes where c.ClassId == classdetail.ClassId select c).FirstOrDefault() ??
                        new Class();
                    Mapper.Map(classdetail, mclass2, typeof(ClassViewModel2), typeof(Class));

                    if (fmainimage != null)
                    {
                        int length = fmainimage.ContentLength;
                        mclass.MainImage = new byte[length];
                        fmainimage.InputStream.Read(mclass.MainImage, 0, length);
                        mclass2.MainImage = new byte[length];
                        fmainimage.InputStream.Read(mclass2.MainImage, 0, length);
                    }
                    if (fthumbnail != null)
                    {
                        int length1 = fthumbnail.ContentLength;
                        mclass.ThumbNail = new byte[length1];
                        fthumbnail.InputStream.Read(mclass.ThumbNail, 0, length1);
                        mclass2.ThumbNail = new byte[length1];
                        fthumbnail.InputStream.Read(mclass2.ThumbNail, 0, length1);
                    }
                    if (classdetail.ClassId == 0)
                    {
                         //assign default if not assigned
                        Studio currentstudio = _db.Studios.Find(up.StudioId);

                        currentstudio.Classes.Add(mclass2);
                    }
                    else
                    {
                        _db.Entry(mclass).State = EntityState.Modified;
                    }
                    _db.SaveChanges();
                    return RedirectToAction(Actions.Details(mclass.ClassId));
                }
            }
            classdetail.Trainers = (from t in _db.Trainers where t.Studio.StudioId == up.StudioId select t).ToList()
                                                                                                           .Select(
                                                                                                               tr =>
                                                                                                               new SelectListItem
                                                                                                                   {
                                                                                                                       Value
                                                                                                                           =
                                                                                                                           tr
                                                                                                                   .TrainerId
                                                                                                                   .ToString
                                                                                                                   (),
                                                                                                                       Text
                                                                                                                           =
                                                                                                                           tr
                                                                                                                               .FirstName +
                                                                                                                           " " +
                                                                                                                           tr
                                                                                                                               .LastName
                                                                                                                   });
            return View(classdetail);
        }

,这是我的观点:

 @using (Html.BeginForm(MVC.Class.Edit(), FormMethod.Post, new { @class = "form label-inline", name = "iform", enctype = "multipart/form-data" }))
                    {
                        @Html.HiddenFor(model => model.ClassId)
                        <div class="formSep">
                            <label class="req">Name</label>
                            <span style="color:red">@Html.ValidationMessageFor(model => model.Name)</span>
                            @Html.EditorFor(model => model.Name, new { @class = "medium" })
                        </div>
                        <div class="formSep">
                            <label class="req">Description</label>
                            <span style="color:red">@Html.ValidationMessageFor(model => model.Description)</span>
                            @Html.TextAreaFor(model => model.Description, new { style = "width: 420px; height: 6em;" })
                        </div>                        
                        <div class="formSep">
                            <label class="req">Instructional Video Description</label>
                            <span style="color:red">@Html.ValidationMessageFor(model => model.InstructionalDescription)</span>
                            @Html.TextAreaFor(model => model.InstructionalDescription, new { style = "width: 420px; height: 6em;" })
                        </div>
                        if(Model.ClassId == 0){
                            <div class="formSep">
                           @Html.CheckBoxFor(model => model.IsRewatchable, new { style = "display:inline;" })
                            <label style="display: inline;" class="">&nbsp;The videos in the class can be watched any number of times</label>
                        </div>
                        }
                        else{
                            <div class="formSep" style="display:none">
                           @Html.CheckBoxFor(model => model.IsRewatchable, new { style = "display:inline;" })
                            <label style="display: inline;" class="">&nbsp;The videos in the class can be watched any number of times</label>
                        </div>
                        }
                        if (Model.ClassId == 0) {
                        <div class="formSep">
                            @Html.CheckBoxFor(model => model.IsAttendable, new { style = "display:inline;" })
                            <label style="display: inline;" class="">&nbsp;Attendance is recorded for this class</label>
                        </div>
                        }
                        else
                        {
                           <div class="formSep" style="display:none">
                            @Html.CheckBoxFor(model => model.IsAttendable, new { style = "display:inline;" })
                            <label style="display: inline;" class="">&nbsp;Attendance is recorded for this class</label>
                        </div> 
                        }
                        <div class="formSep">
                            <label class="req">Class Image</label>
                            <span style="color:red">@Html.ValidationMessageFor(model => model.MainImage)</span>
                            <input type="file" name="fmainimage" id="fmainimage" /><br />
                            @if (Model.ClassId != 0)
                            {
                                if (Model.MainImage != null)
                                {
                                <img src="@Url.Action(MVC.Class.GetMainImage(Model.ClassId))"/>
                                }
                                else
                                {
                                <text>No Main Image Exists</text>
                                }
                            }
                        </div>
                        <div class="formSep">
                            <label class="req">Thumbnail</label>
                            <span style="color:red">@Html.ValidationMessageFor(model => model.ThumbNail)</span>
                            <input type="file" name="fthumbnail" id="fthumbnail" /><br />
                            @if (Model.ClassId != 0)
                            {
                                if (Model.ThumbNail != null)
                                {
                                <img src="@Url.Action(MVC.Class.GetThumbnail(Model.ClassId))"/>
                                }
                                else
                                {
                                <text>No Thumbnail Exists</text>
                                }
                            }
                        </div>
                        <div class="formSep">
                            <label class="req">Trainer</label>
                            <span style="color:red">@Html.ValidationMessageFor(model => model.Trainer)</span>
                            @Html.DropDownListFor(model => model.TrainerId, new SelectList(Model.Trainers, "value", "text", @Model.TrainerId))
                        </div>      
                        <div class="formSep">
                            <button type="submit" class="button-small-theme rounded3">SAVE</button>&nbsp;&nbsp;<a href="@Url.Action(MVC.Class.Details(Model.ClassId))" class="button-small-cancel rounded" style="padding: 12px 10px 9px;">CANCEL</a>
                        </div>
                    }

如果项目的ID为0,它将使用相同的编辑视图,但它将创建一个新的项目

Required Byte[] on View Model

即使您的byte[]为null,也可以保存模型。IsValid不会捕获"错误"。如果byte[]为空,则应该重定向回view()。

在保存之前添加这个。

if (fthumbnail == null || fthumbnail == null)
{
    ModelState.AddModelError("_FORM", "Your little error message to the user.");
    return View(classdetail);
}

通过覆盖IsValid方法创建您自己的数据验证

    public class MyAmazingValidations : RequiredAttribute
   {
      public override bool IsValid(object value)
     {
         bool isValid = base.IsValid(value);
         if(isValid)
         {
             ICollection collection = value as ICollection;
            if(collection != null)
              {
                 isValid = collection.Count != 0;
              }  
       }  
        return isValid;
    }
  }

然后去你的模型和装饰你的属性:

    [MyAmazingValidations (ErrorMessage="You made a big mistake right now!")]
    public byte[] someProperty{ get; set; }