0

我的模型继承自一个接口:

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();
      }  
}

项目搜索:

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)
{..}
4

1 回答 1

2

您需要指定正确的前缀才能绑定子类型。例如,如果您想绑定到模型Name属性的Search属性,您的文本框必须命名为: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) %>
于 2010-03-23T13:26:38.453 回答