NHaml的强烈视图?

时间:2009-11-24 14:05:53

标签: c# asp.net-mvc strongly-typed-view nhaml

我有一个强类型视图,并希望在NHaml页面中使用它。

使用WebForms引擎,我将在<%@ Page%>指令或代码隐藏文件中描述ViewData类型。

我将如何在NHaml中进行此操作?

3 个答案:

答案 0 :(得分:1)

this页面上有一个补丁(搜索NHaml)来执行此操作。我不知道它是否有效。这需要来自MvcContrib的NHaml。

  

修补NHaml View Engine以进行升级   它适用于包含MVC预览版3   NHamlView上的Model属性   允许强类型访问   ViewDataDictionary中的模型数据   因为接口属性是非   通用,我们喜欢强烈打字   View中的ViewData访问权限..   例如预览2下的ViewData.Property   将成为Model.Property下   预览3 2008年5月30日应用:应用   在修订版375中。

答案 1 :(得分:1)

鲍里斯

如果我理解正确你只想要一个强类型的nhaml视图?

如果是这种情况,svn中有一个示例项目可以执行此操作。看看

http://nhaml.googlecode.com/svn/trunk/src和NHaml.Samples.Mvc.CSharp项目

这里有一些提取的代码

<强>控制器

public class ProductsController : Controller
{
    private readonly NorthwindDataContext northwind = new NorthwindDataContext(
        ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString );


    public ActionResult Edit( int id )
    {
        var viewData = new ProductsEditViewData { Product = northwind.GetProductById( id ) };

        viewData.Categories = new SelectList( northwind.GetCategories(), "CategoryID", "CategoryName", viewData.Product.CategoryID );
        viewData.Suppliers = new SelectList( northwind.GetSuppliers(), "SupplierID", "CompanyName", viewData.Product.SupplierID );

        return View( "Edit", viewData );
    }

}

查看

%h2= ViewData.Model.Product.ProductName
%form{action='#{Url.Action("Update", new { ID=ViewData.Model.Product.ProductID \})}' method="post"}
  %table
    %tr
      %td Name:
      %td= Html.TextBox("ProductName", ViewData.Model.Product.ProductName)
    %tr
      %td Category:
      %td= Html.DropDownList("CategoryID", ViewData.Model.Categories, (string)null)
    %tr
      %td Supplier:
      %td= Html.DropDownList("SupplierID", ViewData.Model.Suppliers, (string)null)
    %tr
      %td Unit Price:
      %td= Html.TextBox("UnitPrice", ViewData.Model.Product.UnitPrice.ToString())
  %p
  - Html.RenderPartial(@"_Button")

查看模型

public class ProductsEditViewData
{
    public Product Product { get; set; }
    public SelectList Suppliers { get; set; }
    public SelectList Categories { get; set; }
}

希望有所帮助

答案 2 :(得分:1)

  

我会在中描述ViewData类型   &lt;%@ Page%&gt;指令或在   代码隐藏文件。

     

我将如何在NHaml中进行此操作?

不需要这样做。您可以只使用模型而不指定其类型,它将起作用。例如:

%h2= Model.PageTitle
  %p= Model.UserMessageOrSomething

这是因为编译了NHAML视图。因此,当模型上的所有属性都正确时(名称,类型等),视图将被编译(如源代码所示)。