我的模型继承自界面:
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)
{..}
答案 0 :(得分:2)
您需要指定正确的前缀才能绑定子类型。例如,如果要绑定到Model的Name
属性的Search
属性,则必须将文本框命名为:Search.Name
。当您使用Html.TextBoxFor(x=>x.Name)
时,您的文本框名为Name
,并且模型活页夹不起作用。一种解决方法是明确指定名称:
<%= Html.TextBox("Search.Name") %>
或使用editor templates这是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) %>