ASP.NET 模型绑定器和基本类型
我的模型继承自一个接口:
public interface IGrid
{
ISearchExpression Search { get; set; }
.
.
}
public interface ISearchExpression
{
IRelationPredicateBucket Get();
}
模型:
public class Project : IGrid
{
public ISearchExpression Search { get; set; }
public Project()
{
this.Search = new ProjectSearch();
}
}
ProjectSearch:
public class ProjectSearch: ISearchExpression
{
public string Name { get; set; }
public string Number { get; set; }
public IRelationPredicateBucket Get()
{...}
}
主视图中的强类型部分视图:
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<ProjectSearch>" %>
<%= Html.TextBoxFor(x=>x.Name)%>
<%= Html.TextBoxFor(x => x.Number)%>
....
当我提交表单时, Search
属性未正确绑定。一切都是空的。该操作采用 ProjectSearch
类型的参数。
为什么 Search
没有按预期绑定?
编辑
动作
public virtual ActionResult List(Project gridModel)
{..}
My model inherits from an interface:
public interface IGrid
{
ISearchExpression Search { get; set; }
.
.
}
public interface ISearchExpression
{
IRelationPredicateBucket Get();
}
The model:
public class Project : IGrid
{
public ISearchExpression Search { get; set; }
public Project()
{
this.Search = new ProjectSearch();
}
}
The ProjectSearch:
public class ProjectSearch: ISearchExpression
{
public string Name { get; set; }
public string Number { get; set; }
public IRelationPredicateBucket Get()
{...}
}
And the strong typed partialview in the main view:
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<ProjectSearch>" %>
<%= Html.TextBoxFor(x=>x.Name)%>
<%= Html.TextBoxFor(x => x.Number)%>
....
When I submit the form, the Search
property don't get bound properly. Everything is empty.The action takes an argument of ProjectSearch
type.
Why the Search
don't get bound as supposed ?
EDIT
The action
public virtual ActionResult List(Project gridModel)
{..}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要指定正确的前缀才能绑定子类型。例如,如果要绑定到模型的
Search
属性的Name
属性,则文本框必须命名为:Search.Name
。当您使用Html.TextBoxFor(x=>x.Name)
时,您的文本框被命名为Name
并且模型绑定器不起作用。一种解决方法是显式指定名称:或使用 编辑器模板,这是 ASP.NET MVC 2.0 中的一项新功能
更新:
根据评论部分中提供的其他详细信息,这里有一个应该有效的示例:
模型:
控制器:
视图 - ~/Views /Home/Index.aspx:
查看 - ~/Views/Home/SearchTemplate.ascx:
You need to specify the correct prefix in order to bind sub types. For example if you want to bind to
Name
property of theSearch
property of the Model your textbox must be named:Search.Name
. When you useHtml.TextBoxFor(x=>x.Name)
your textbox is namedName
and the model binder doesn't work. One workaround is to explicitly specify the name:or use editor templates which is a new feature in ASP.NET MVC 2.0
UPDATE:
Based on the additional details provided in the comments section here's a sample that should work:
Model:
Controller:
View - ~/Views/Home/Index.aspx:
View - ~/Views/Home/SearchTemplate.ascx: