I have a top10 table (like top 10 restaurants say). Each top 10 row can have up to 10 top10items associated.

Models

public class Top10
{
    public Guid Id { get; set; }

    [Required(ErrorMessage="Title Required")]
    public string Title { get; set; }
}

public class Top10Item
{
    public Guid Id { get; set; }
    public Guid Top10Id { get; set; }
    public Guid PlaceId { get; set; }
    public Int16 Position { get; set; }

    public Place place { get; set; }
}

View Model

public class Top10ItemsPlaceDropdown
{
    public Top10 top10 { get; set; }

    [Display(Name = "Place")]
    public Guid SelectedPlaceId { get; set; }

    public IEnumerable<Place> Places { get; set; }

    public IEnumerable<SelectListItem> PlaceItems
    {
        get
        {
            return new SelectList(Places, "Id", "PlaceName");
        }
    }

    public IEnumerable<Top10Item> items { get; set; }
}

I bind the ViewModel to a View.

I use it to populate a dropdown on the page, and populate a grid of items for the top 10. The user can then select an item from the dropdown - which is then posted by the [httpPost] method when the user submits the form.

The problem - if it is a problem - is that when the view loads [httpGet] - all properties - and those of all sub-objects are valid. However when the view posts back to the controller [httpPost], many are empty (invalid) because on the view they aren't in form fields and don't get posted back (they don't need to be).

This means Model.IsValid == false. If I had a validation summary on the page - this would invoke it.

This doesn't seem like good practice - but what should i do about this? The model serves my purposes when the page loads - but all I need when the page is posted is top10Id and SelectedPlaceId.

有帮助吗?

解决方案

The first GET returns a View built from a valid ViewModel.

The POST then returns a View built from an invalid ViewModel, giving validation warnings.

If the second View is the same as the first, the ViewModel must be valid, or the display won't be correct, because of the missing properties.

If the second View is different from the first, you should use another ViewModel, which contains only the properties needed for the second View, without validation warnings

许可以下: CC-BY-SA归因
scroll top