[英]ASP.NET Model Binder and base type
我的模型继承自接口:
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()
{...}
}
而主视图中的强类型的partialview:
<%@ 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)
{..}
您需要指定正确的前缀才能绑定子类型。 例如,如果您想绑定到Model的Search
属性的Name
属性,则您的文本框必须命名为: Search.Name
。 当您使用Html.TextBoxFor(x=>x.Name)
您的文本框将被命名为Name
,而模型绑定程序将不起作用。 一种解决方法是显式指定名称:
<%= Html.TextBox("Search.Name") %>
或使用ASP.NET MVC 2.0中的新功能编辑器模板
更新:
根据评论部分提供的其他详细信息,这里是一个应该起作用的示例:
模型:
public interface IRelationPredicateBucket
{ }
public interface ISearchExpression
{
IRelationPredicateBucket Get();
}
public interface IGrid
{
ISearchExpression Search { get; set; }
}
public class ProjectSearch : ISearchExpression
{
public string Name { get; set; }
public string Number { get; set; }
public IRelationPredicateBucket Get()
{
throw new NotImplementedException();
}
}
public class Project : IGrid
{
public Project()
{
this.Search = new ProjectSearch();
}
public ISearchExpression Search { get; set; }
}
控制器:
public class HomeController : Controller
{
public ActionResult Index()
{
return View(new Project());
}
[HttpPost]
public ActionResult Index(ProjectSearch gridModel)
{
// gridModel.Search should be correctly bound here
return RedirectToAction("Index");
}
}
查看-〜/ Views / Home / Index.aspx:
<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<Models.Project>" %>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<% using (Html.BeginForm()) { %>
<% Html.RenderPartial("~/Views/Home/SearchTemplate.ascx", Model.Search); %>
<input type="submit" value="Create" />
<% } %>
</asp:Content>
查看-〜/ Views / Home / SearchTemplate.ascx:
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<Models.ProjectSearch>" %>
<%= Html.TextBoxFor(x => x.Name) %>
<%= Html.TextBoxFor(x => x.Number) %>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.