質問

I get the following error when I hit the postback:

The model item passed into the dictionary is of type 'Test.Models.ProductsModel', but this dictionary requires a model item of type 'Test.Models.AttributeModel'

What I want to achieve is hopefully pretty selfexplanatory with the code below

 public class ProductsModel
 {
    [Required]
    public string Name { get; set; }

    public AttributeModel AttributeModel { get; set; }
}

public class AttributeModel
{
    [Required]
    public int Size { get; set; }
}

Create.cshtml

@model Test.Models.ProductsModel      
@using (Html.BeginForm()) {
    @Html.ValidationMessageFor(m => m.Name)
    @Html.TextBoxFor(m => m.Name)

    @Html.Partial("_Attribute", Model.AttributeModel)

    <input type="submit" value="Click me" />
}

_Attribute.cshtml

@model Test.Models.AttributeModel

<h2>_Attribute</h2>

@Html.ValidationMessageFor(m => m.Size)
@Html.TextBoxFor(m => m.Size)

Controller

[HttpGet]
public ActionResult Create()
{
    ProductsModel model = new ProductsModel { AttributeModel = new AttributeModel() };
    return View(model);
}

[HttpPost]
public ActionResult Create(ProductsModel m)
{
    return View(m);
}

EDIT - SOLUTION

I found that the problem occurs because no input binds to AttributeModel which means that it will be null in ProductsModel, resulting in the follow errouneous statement:

@Html.Partial("_Attribute", null)

The solution is to use the HTML helper "EditorFor". Have a look at Complex models and partial views - model binding issue in ASP.NET MVC 3

役に立ちましたか?

解決

I suspect your problem is in your postback action. I would thing that the View that it is getting has AttributeModel as null so when you are calling the Partial you are actually calling it with ("_Attribute", null) and if the model is null then it will pass the current model in instead.

You need to make sure you have a valid AttributeModel on your ProductsModel.

他のヒント

You need to initialize the AttributeModel property of your class like

public class ProductsModel
{
   [Required]
   public string Name { get; set; }
   public AttributeModel AttributeModel { get; set; }
   public ProductsModel()
   {
     this.AttributeModel =new AttributeModel();
    }
}

Because initially AttributeModel property is set to null.

The Error is very descriptive.Its telling what is done wrong.

Your partial view requires object of type Test.Models.AttributeModel but you are passing object of type Test.Models.ProductsModel

Here you have set Model to Test.Models.AttributeModel

@model Test.Models.AttributeModel

<h2>_Attribute</h2>

@Html.ValidationMessageFor(m => m.Size)
@Html.TextBoxFor(m => m.Size)

Change you partial view Model to Test.Models.AttributeModel or pass object of type Test.Models.AttributeModel from the action.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top