I have a problem where I have passed two models into a view model. In a particular view I only want to check validation for two properties, one from each model in the view model.
However both models contain other properties each with their own data annotations, which means the form won't submit until all annotations have been satisfied even though they aren't on the form.
So I need to find a way to only check validation for specific properties in the two models, but still save the whole object to the database if it passes the validation check.
Code example
Models
public class FirstModel
{
public int Id { get; set; }
[Required]
public string Prop2 { get; set; }
[Required]
public DateTime Prop3 { get; set; }
}
public class SecondModel
{
public int Id { get; set; }
[Required]
public string Prop2 { get; set; }
[Required]
public int Prop3 { get; set; }
}
public class ThirdModel
{
public int Id { get; set; }
[Required]
public FirstModel FirstModel { get; set; }
[Required]
public SecondModel SecondModel { get; set; }
}
View Model
public class ThirdFormViewModel
{
// maybe I can do something here?
public FirstModel FirstModel { get; set; }
public SecondModel SecondModel { get; set; }
}
Controller Post Action
[HttpPost]
public ActionResult CreateThirdModel(ThirdModel newThirdModel)
{
var firstModel = _context.FirstModels.Single(c => c.Id == newThirdModel.Id);
var secondModel = _context.SecondModels.Single(c => c.Id == newThirdModel.SecondModel.Id);
if (!ModelState.IsValid)
{
var viewModel = new ThirdFormViewModel
{
FirstModel = firstModel,
SecondModel = secondModel
};
return View("ThirdModelForm", viewModel);
}
var thirdModel = new ThirdModel
{
FirstModel = firstModel,
SecondModel = secondModel,
};
_context.ThirdModels.Add(thirdModel);
_context.SaveChanges();
return RedirectToAction("Index");
}
View
@model MyProject.ViewModels.ThirdFormViewModel
@using (Html.BeginForm()
{
<div class="form-group">
@Html.TextBoxFor(m => m.FirstModel.Prop2)
</div>
<div class="form-group">
@Html.TextBoxFor(m => m.SecondModel.Prop3)
</div>
<button type="submit" class="btn btn-primary">Save</button>
}