【问题标题】:send object through ViewData.Model in asp.net mvc在 asp.net mvc 中通过 ViewData.Model 发送对象
【发布时间】:2015-04-02 19:08:37
【问题描述】:

我需要你的帮助。

我尝试使用 ViewData.Model 将对象从视图传递给控制器​​

这是控制器中的索引方法

public ActionResult Index()
    {
        ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";
        dynamic stronglytyped = new { Amount = 10, Size = 20 };
        List<dynamic> ListOfAnynomous = new List<object> { new { amount = 10 } };


         ViewData.Model =  ListOfAnynomous[0];
        return View();
    }

这是视图部分

        <div>
             @Model.amount 

        </div>

这是错误的

'object' does not contain a definition for 'amount'

谁能帮帮我。

【问题讨论】:

  • 不要使用objectdynamic。创建视图模型并将视图模型传递给视图。
  • @StephenMuecke 谢谢,我得到了解决方案,但请你解释一下为什么编译器看不到动态对象定义。
  • @StephenMuecke 我希望将您的评论作为接受它的答案
  • 因为你传递了一个匿名对象。匿名类型是内部的,因此它们的属性不能在其定义的程序集之外看到。 This article 给出了很好的解释。

标签: asp.net-mvc asp.net-mvc-4


【解决方案1】:

抛出异常是因为您传递了一个匿名对象。匿名类型是内部的,因此它们的属性不能在其定义的程序集之外看到。 This article 给出了很好的解释。

虽然您可以使用 html 助手来呈现属性,例如

@Html.DisplayFor("amount")

您还将失去智能感知,您的应用将难以调试。

改为使用视图模型来表示您想要显示/编辑的内容并将模型传递给视图。

【讨论】:

    【解决方案2】:

    您的代码错误。 如果您想使用 model 对象,请将其传递给视图:

    return View(ListOfAnynomous[0]);
    

    之后您就可以使用“模型”属性了。 ViewData 是另一个与模型属性无关的容器。

    最后你的方法会是这样的:

    public ActionResult Index()
        {
            ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";
            dynamic stronglytyped = new { Amount = 10, Size = 20 };
            List<dynamic> ListOfAnynomous = new List<object> { new { amount = 10 } };
    
    
             // ViewData.Model =  ListOfAnynomous[0];
            return View(ListOfAnynomous[0]);
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-11-21
      • 2016-06-22
      • 2018-11-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-03
      相关资源
      最近更新 更多