Type conversion error when passing model to partial

I get the following error when I hit the postback:

The model element passed to the dictionary is of type "Test.Models.ProductsModel", but for this dictionary a model element of type "Test.Models.AttributeModel" is required

What I want to achieve, hopefully, will be pretty self-evident 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);
}

EDITING - SOLUTION

I found that the problem occurs because no input is associated with the AttributeModel, which means that it will be null in the ProductsModel, which will result in the following erronomic statement:

@Html.Partial("_Attribute", null)

HTML- "EditorFor". - ASP.NET MVC 3

+4
3

, . , View, , AttributeModel null, , Partial, ("_Attribute", null), , .

, AttributeModel ProductsModel.

+2

AttributeModel ,

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

AttributeModel null.

+1

. , .

Test.Models.AttributeModel, Test.Models.ProductsModel

Model Test.Models.AttributeModel

@model Test.Models.AttributeModel

<h2>_Attribute</h2>

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

Test.Models.AttributeModel Test.Models.AttributeModel .

0

Source: https://habr.com/ru/post/1540672/


All Articles