是否可以在 ASP.net MVC 2 中将匿名或动态视图模型传递给视图并返回?
我在一个 asp.net MVC 2 项目中,并且有一个继承自 System.Web.Mvc.ViewPage
public ActionResult Index()
{
dynamic model = new {Value1= string.Empty, Value2= string.Empty};
return View(model);
}
[HttpPost]
public ActionResult Index(dynamic model)
{
var value1 = model.Value1;
var value2 = model.Value2;
// do something here.
}
对于我的观点,我目前有以下内容:
<% using(Html.BeginForm("Index", "Test"))
{
%>
<div>
<label for="Value1">Value1:</label>
<%=Html.TextBox("Value1", Model.Value1 as string) %>
</div>
<div>
<label for="Value2">Value2:</label>
<%=Html.Password("Value2", Model.Value2 as string) %>
</div>
<div>
<input type="submit" value="Submit" />
</div>
<% } %>
上面的代码产生“'object does not contains a Define of 'Value1'”的错误,并突出显示 Value1 的 Html.TextBox 行。
我尝试编写自己的 html 表单和输入标记(确保包含 name 和 id 属性)并将值设置为 Model.Value1 和 Model.Value2。这可以渲染页面(和测试值);但是,提交后我收到与以前相同的错误。
是否可以在 ASP.Net MVC2 中为我的 ViewModel 使用匿名和/或动态类型,或者我是否被迫编写大量我希望避免的 DTO。
I'm on a asp.net MVC 2 project and have a view that inherits from System.Web.Mvc.ViewPage<dynamic>. I would like to do something like below:
public ActionResult Index()
{
dynamic model = new {Value1= string.Empty, Value2= string.Empty};
return View(model);
}
[HttpPost]
public ActionResult Index(dynamic model)
{
var value1 = model.Value1;
var value2 = model.Value2;
// do something here.
}
For my view, I currently have the below:
<% using(Html.BeginForm("Index", "Test"))
{
%>
<div>
<label for="Value1">Value1:</label>
<%=Html.TextBox("Value1", Model.Value1 as string) %>
</div>
<div>
<label for="Value2">Value2:</label>
<%=Html.Password("Value2", Model.Value2 as string) %>
</div>
<div>
<input type="submit" value="Submit" />
</div>
<% } %>
The above code yields an error of "'object does not contain a definition of 'Value1'" and highlights the Html.TextBox line for Value1.
I have attempted to just write my own html form and input tags (making sure to include both name and id attributes) and setting the value to Model.Value1 and Model.Value2. This works to render the page (and test values); however, upon submission I get the same error as before.
Is it possible to use anonymous and/or dynamic types for my ViewModels in ASP.Net MVC2 or am I forced to write a ton of DTOs which I'm hoping to avoid.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的,如果您将视图声明为具有动态模型,这是可能的:
也就是说,如果您使用 MVC 2 的默认模板 (
Html.EditorForModel()
),您甚至不必这样做。Yes, it's possible, if you declare your view as having a dynamic model:
That said, if you use MVC 2's default templates (
Html.EditorForModel()
) you don't even have to do that.在 .NET 4.0 上,匿名类型可以轻松转换为 ExpandoObjects,因此所有问题都可以通过转换本身的开销来解决。
请查看此处
On .NET 4.0 Anonymous types can easily be converted to ExpandoObjects and thus all the problems is fixed with the overhead of the conversion itself.
Check out here