Search code examples
c#asp.net-coreviewmodel

How to use 2 view models in 1 page - one for displaying information and one for reading information


I have a page in which I am both displaying information to the user and reading information from the user, which i need to validate. The problem is that I can only use one view model per page. I have this view model for displaying information:

public class ProductDisplayModel
{
    public ProductDisplayModel(List<Review> reviews, Product product)
    {
        Reviews = reviews;
        Product = product;
    }

    public List<Review> Reviews { get; set; }

    public Product Product { get; set; }
}

And I have this view model for reading and validating the user's input:

public class CreateReviewModel
{
    public CreateReviewModel() { }

    [MaxLength(100)]
    [Required]
    public string Comment { get; set; }

    public int Rating { get; set; }
}

You may suggest that I combine the 2 view models into one. The problem then is that I cannot use ModelState.IsValid, because the part for the displaying info will always be null, when it gets to the http post method, thus the ModelState.IsValid will always be false.


Solution

  • Creating a compound model is good idea and you still can use the ModelState.IsValid to check the model state. But in this case you can mark the displaying info ProductDisplayModel to be ignored when parsing/validating on the controller side by using the [ValidateNever] attribute, like below:

    public class DataModel
    {
        [ValidateNever]
        public ProductDisplayModel Display { get;set; }
        public CreateReviewModel ClientData { get; set; } 
    }