I have a View Model that has a Byte[] property and it is required at the moment a user creates a new item, here is my model:

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; }
}

but if the Byte[] is null it will continue creating the item anyway, it works fine with the other properties so I am not sure how to include a validation for this.

This is my Edit Controler:

[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);
        }

and this is in my view:

 @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>
                    }

If the ID of the item is 0 it will use the same edit View but it will create a new Item

有帮助吗?

解决方案

Well you are saving the model even if your byte[] is null, the Model.IsValid wont catch the "error". You should redirect back the view() it the byte[] is null.

Add this before your save.

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

其他提示

Create your own data validations by overriding the IsValid Method

    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;
    }
  }

then go to ur model and decorate your property :

    [MyAmazingValidations (ErrorMessage="You made a big mistake right now!")]
    public byte[] someProperty{ get; set; }
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top