I am using MVC 5 with entity framework 6 I have model contain a Required property
public class Slider
{
public int id { get; set; }
[NotMapped]
[ValidateFileAttributeForImages(ErrorMessageResourceName = "SliderFileError", ErrorMessageResourceType = typeof(GlobalRes))]
[Display(Name = "SliderFile", ResourceType = typeof(GlobalRes))]
public HttpPostedFileBase File { get; set; }
public string ImagePath { get; set; }
}
I need to remove this required Data Annotations so I can update or edit this model as I the user can upload an image or not in the edit .. so I found this post Disable Required validation attribute under certain circumstances
so I did a ViewModel contain same properties but without the required.
public class SliderEditViewModel
{
public int id { get; set; }
[NotMapped]
[Display(Name = "SliderFile", ResourceType = typeof(GlobalRes))]
public HttpPostedFileBase File { get; set; }
public string ImagePath { get; set; }
}
in my action result
public ActionResult EditSliderLayer(SliderEditViewModel slider, string Comand, HttpPostedFileBase File)
{
using (DBContext db = new DBContext())
{
if (ModelState.IsValid)
{
if (Comand == GlobalRes.EditBTN)
{
db.Entry(slider).State = EntityState.Modified;
db.SaveChanges(); <!-- here i got error -->
return View();
}
else if (Comand == GlobalRes.DeleteBTN)
{
}
}
List<Slider> SliderName = db.Slider.ToList();
ViewBag.SliderLayerName = new SelectList(SliderName, "id", "Header");
return View(slider);
}
}
I get error
The entity type SliderEditViewModel is not part of the model for the current context.
ValidateFileAttributeForImages
public class ValidateFileAttributeForImages : RequiredAttribute
{
public override bool IsValid(object obj)
{
var file = obj as HttpPostedFileBase;
if (file == null)
{
return false;
}
if (file.ContentLength > 1 * 1024 * 1024)
{
return false;
}
try
{
if (Path.GetExtension(file.FileName) == ".png" || Path.GetExtension(file.FileName) == ".jpg" ||
Path.GetExtension(file.FileName) == ".jpeg" || Path.GetExtension(file.FileName) == ".bmg ")
{
return true;
}
}
catch
{
}
return false;
}
}