Nullable Model within Model

Topics: Writing modules
May 22, 2012 at 7:31 PM

Can't seem to figure how to do this or if it's possible. This module does not use ContentItems at all.

I have a model that contains instances of other models:

    public class MetricRecord
        public virtual int Id { get; set; }
        [DisplayName("Metric Type")]
        public virtual MetricTypeRecord MetricType { get; set; }
        public virtual QualifierRecord Qualifier { get; set; }
        public virtual ScorecardRecord Scorecard { get; set; }
        [DisplayName("Metric ID Name")]
        public virtual string MetricIdName { get; set; }

So, MetricRecord contains a MetricTypeRecord, QualifierRecord, and ScorecardRecord

I'd like QualifierRecord and ScorecardRecord optional on the MetricRecord so that they can be null.

I can't seem to figure out how to configure my Controller to allow for null values for these though.

I'm passing in a FormCollection to my Action so I can do this, since the controls for selecting these items are dropdowns:

metric.MetricType = _metrictypeService.Get(int.Parse(collection["MetricType.Id"]));

This one works great because it's required and I don't have the option in the dropdown to not select an item.

For Scorecard and Qualifier, the first item in the dropdown is "Select an item" which passes a null value. I thought I could do this in the Controller:

if (collection["Scorecard.Id"] != null)
                metric.Scorecard = _scorecardService.Get(int.Parse(collection["Scorecard.Id"]));
    metric.Scorecard = null;

but it gives me an error. I can select something from the dropdown list and it updates fine.

Any ideas on how I configure the Controller to leave Scorecard and Qualifier null if an item is not selected?

Thanks so much for the assistance.

May 22, 2012 at 11:23 PM

What is the exact error you're getting, and on which line?

As an aside, you may want to consider using View Models instead of directly using Domain Models with model binding.
Having for example a "MetricViewModel" will enable you to work with nullable integers for the IDs: int? ScorecardId, int? QualifierId, etc. without having to manually parse them. It's just a thought though, and has probably nothing to do with the error.