繁体   English   中英

传递到字典中的模型项的类型为“System.String”,但此字典需要类型为“JFS.Data.Model.Address”的模型项。

[英]The model item passed into the dictionary is of type 'System.String', but this dictionary requires a model item of type 'JFS.Data.Model.Address'

我对MVC很陌生,但一直在稳步前进,但是我最近遇到了一个问题,尽管在类似主题上阅读过类似的帖子,但我似乎无法克服这个问题。

我有一个如下模型(简化为简洁)

public virtual int Id { get; set; }

public virtual string Name { get; set; }

public virtual Address Address { get; set; }

我有一个强类型视图如下:

@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>

我有一个共享的EditorTemplate for Country字段,如下所示:

 @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);
        }
    }

我理解这个问题,但不确定如何最好地克服它,任何建议都将非常感激。

尽管@ProNotion已经回答了你的特定场景,但是在将null传递给视图或模板之前,我遇到了这个问题。 它可能会帮助其他人这样做。

在您的主视图中替换:

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

有:

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

顺便说一下,如果您正在为Address模型编写共享编辑器模板,您可能希望在此模板中包含其他属性,例如AddressLine1

您只需要传递Address属性:

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

您正在尝试传递string s的Address属性,而类型的要求是Address

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM