当将模型传递给局部视图时,出现类型转换错误。

4
当我点击postback时,出现以下错误: 字典中传递的模型项目类型为“Test.Models.ProductsModel”,但该字典需要一个模型项目类型为“Test.Models.AttributeModel” 我的目标很明显,就是通过下面的代码实现。
 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)

控制器

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

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

编辑 - 解决方案

我发现该问题是因为没有将输入绑定到AttributeModel,这意味着在ProductsModel中它将为空,导致以下错误语句:

@Html.Partial("_Attribute", null)

解决方案是使用HTML助手“EditorFor”。请参考ASP.NET MVC 3中复杂模型和部分视图的模型绑定问题


我想我已经做到了?看一下我的控制器。 - Peter
在“Create”或“_Attribute”视图中还有其他内容吗? - user61470
没有,我已经全部发布了。除了@ViewBag.Title之外,但那应该是无关紧要的吧? - Peter
3个回答

2
我猜测你的问题出在postback操作上。我认为它得到的视图中AttributeModelnull,所以当你调用Partial时实际上是使用("_Attribute", null),如果模型为空,则会传递当前模型。
你需要确保在ProductsModel上有一个有效的AttributeModel

非常感谢,那确实是问题所在!但是似乎AttributeModel始终为空。为什么我的部分视图中的输入不会绑定到该模型呢? - Peter
我不确定。模型绑定的魔力并不总是我完全理解的东西。也许需要另外一个问题来解决这个问题。 - Chris

1
你需要初始化你的类的AttributeModel属性,如下:
public class ProductsModel
{
   [Required]
   public string Name { get; set; }
   public AttributeModel AttributeModel { get; set; }
   public ProductsModel()
   {
     this.AttributeModel =new AttributeModel();
    }
}

因为最初 AttributeModel 属性被设置为 null。


0

错误信息非常具体,它告诉你哪里出了问题。

你的部分视图需要类型为Test.Models.AttributeModel的对象,但你传递的是类型为Test.Models.ProductsModel的对象。

在这里,你已经将模型设置为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的对象。


但是为什么?Model.AttributeModel 不会返回 Test.Models.AttributeModel 吗? - Peter
如果您展示您的操作,那将更容易帮助。 - Ehsan Sajjad
@EhsanSajjad: 然后将传递一个ProductsModel到partial中,该partial期望一个AttributeModel。 - Chris
谢谢大家。我已经找到了解决方案。它已经更新在问题中了。我不知道这是否是惯例,但如果其他人有同样的问题,这可能会更容易些。 - Peter
这个答案完全是错误的。传递了正确的对象类型,但它未初始化(即为null),因此传递了父对象... -1来反转明显“错误”的赞同你似乎得到了很多。 :) - iCollect.it Ltd
显示剩余11条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接