将viewbag值分配给模型项会导致mvc4中的错误
本文关键字:mvc4 错误 viewbag 分配 模型 | 更新日期: 2023-09-27 18:17:36
我试图从我的视图传递一个值到我的控制器:
public ActionResult Create(int id)
{
ViewBag.ConferenceRegesterId = id;
return View();
}
你可以看到在create
action中我保存了我的id在viewbag
。我需要这个id在postback,所以我有这个代码为postback:
[HttpPost]
public ActionResult Creat(MvcConference.Models.Details1 ObjDetails)
{
dbcontext.Details1.Add(ObjDetails);
dbcontext.SaveChanges();
List<MvcConference.Models.Details1> lstuser = dbcontext.Details1.ToList();
return View("Index");
}
我使用这个代码分配我的viewbag值给我的模型项目在我的create
视图
@Html.HiddenFor(model => model.ConferenceRegesterId=ViewBag.ConferenceRegesterId)
但最后执行后,我得到了这个错误:
Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.
Compiler Error Message: CS1963: An expression tree may not contain a dynamic operation
我将非常感谢任何帮助
你不能像现在这样在视图中(通过viewbag)为模型的属性赋值,因为你没有创建类的实例。请注意,只有绑定到输入元素的值才会被传回控制器。
稍微改变程序当前的行为方式。控制器中的create
操作将为视图模型创建一个实例并初始化所需的成员(ConferenceRegesterId
)。这个模型将被强绑定到create
视图。
public ActionResult Create(int id)
{
MvcConference.Models.Details1 viewmodel = new MvcConference.Models.Details1();
viewmodel.ConferenceRegesterId = id;
return View(viewmodel);
}
您的create
视图
@model MvcConference.Models.Details1
@using (Html.BeginForm())
{
......
@Html.HiddenFor(model => model.ConferenceRegesterId)
}
现在POST
中的ObjDetails
动作可以访问通过hiddenfield输入元素传递的ConferenceRegesterId
的值
不需要任何模型。这是个简单的问题。当你使用ViewBag时,你必须将这个对象转换为Razor视图中的静态对象。
这样的;
@{
string varName = ViewBag.varName;
}
你不会再看到;
Compiler Error Message: CS1963: An expression tree may not contain a dynamic operation