Asp.net mvc 通过asp.net mvc中的ViewData.Model发送对象
我需要你的帮助 我尝试使用ViewData.Model将对象从视图传递到控制器 这是控制器中的索引方法Asp.net mvc 通过asp.net mvc中的ViewData.Model发送对象,asp.net-mvc,asp.net-mvc-4,Asp.net Mvc,Asp.net Mvc 4,我需要你的帮助 我尝试使用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 };
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();
}
有人能帮我吗。你的代码错了。
如果要使用模型对象,必须将其传递给视图:
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]);
}
public ActionResult Index()
{
ViewBag.Message=“修改此模板以跳转启动ASP.NET MVC应用程序。”;
动态stronglytyped=new{Amount=10,Size=20};
List LISTOFANOMOUS=新列表{new{amount=10}};
//ViewData.Model=ListofAnonomous[0];
返回视图(ListofAnonomous[0]);
}
由于传递了匿名对象,因此引发异常。匿名类型是内部类型,因此无法在其定义程序集之外看到其属性。给出了一个很好的解释
例如,您可以使用html帮助程序呈现属性
@Html.DisplayFor("amount")
您还将失去intellisense,并且您的应用程序将难以调试
而是使用视图模型来表示要显示/编辑的内容,并将模型传递给视图。不要使用
对象
和动态
。创建一个视图模型并将视图模型传递给视图。@StephenMuecke谢谢,我得到了解决方案,但请您解释一下为什么编译器看不到动态对象定义。@StephenMuecke我希望将您的注释作为接受它的答案,因为您传递了一个匿名对象。匿名类型是内部类型,因此无法在其定义程序集之外看到其属性。给出了一个很好的解释。
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]);
}
@Html.DisplayFor("amount")