1
votes

I am quite new to MVC but have been making steady progress however I have recently hit a problem that I can't seem to overcome despite reading a number of similar posts on similar topics.

I have a model as follows (simplified for brevity)

public virtual int Id { get; set; }

public virtual string Name { get; set; }

public virtual Address Address { get; set; }

I have a strongly typed view as follows:

@model JFS.Data.Model.Supplier

@using (Html.BeginForm())
{
    @Html.ValidationSummary(true)  

     <fieldset>
        <legend>Supplier Address</legend>

        <div class="editor-label">
            @Html.LabelFor(model => model.Address.AddressLine1)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Address.AddressLine1)
            @Html.ValidationMessageFor(model => model.Address.AddressLine1)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.Address.Country)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Address.Country)
            @Html.ValidationMessageFor(model => model.Address.Country)
        </div>

    </fieldset>

And I have a shared EditorTemplate for the Country field as follows:

 @model JFS.Data.Model.Address

    @using System.Globalization

    @Html.DropDownListFor(o => o.Country, GetCountries(Model), "Please select")

    @functions
    {
        private static IEnumerable<SelectListItem> GetCountries(object country)
        {
            var regions = CultureInfo.GetCultures(CultureTypes.SpecificCultures)
                            .Select(cultureInfo => new RegionInfo(cultureInfo.LCID))
                            .OrderBy(r => r.EnglishName)
                            .Distinct()
                            .ToList();
            return new SelectList(regions, "TwoLetterISORegionName", "EnglishName", country);
        }
    }

I understand the problem but not sure how best to overcome it, any advice would be very much appreciated.

3

3 Answers

2
votes

Though your particular scenario was already answered by @ProNotion, I have had this issue before when you are passing null into your View or Templates. It may help someone else coming this way.

1
votes

In your main view replace:

@Html.EditorFor(model => model.Address.Country)

with:

@Html.EditorFor(model => model.Address)

By the way if you are writing a shared editor template for an Address model you probably want to include the other properties as well such as AddressLine1 in this template.

1
votes

You need to just pass the Address property:

@Html.EditorFor(model => model.Address)

You are trying to pass the Address properties which are strings, whereas the requirement of type is Address.