2011-07-06 42 views
5

有沒有辦法讓using語句在剃刀視圖中使用泛型方法?比如我想在web表單片斷在剃刀視圖中使用泛型方法

<% using(Html.BeginForm<Controller>(c => c.Method())) 
    { %> 
     Some code 
<% } %> 

轉換成剃刀這樣

@using(Html.BeginForm<Controller>(c => c.Method())) 
{ 
    Some code 
} 

但是,這並不工作,因爲剃刀解釋<Controller>爲HTML標籤。添加圓括號也不起作用,因爲剃鬚刀不包括開始和結束BeginForm的大括號。下面是我嘗試過的不同方法,我再也想不起來了。

@using(Html.BeginForm<Controller>(c => c.Method())) // Interpreted as c# to '<Controller>' 
{             // interpreted as HTML 
    Some code          // interpreted as HTML 
}             // interpreted as HTML 

@(using(Html.BeginForm<Controller>(c => c.Method()))) // Interpreted as c# 
{              // interpreted as HTML 
    Some code           // interpreted as HTML 
}              // interpreted as HTML 

@{using(Html.BeginForm<Controller>(c => c.Method())) // Interpreted as c# 
    {            // interpreted as c# 
     Some code         // interpreted as c# 
    }            // interpreted as c# 
}             // interpreted as c# 

@(using(Html.BeginForm<Controller>(c => c.Method()))) // Interpreted as c# 
@{             // interpreted as c# 
     Some code          // interpreted as c# 
}              // interpreted as c#  

aynone知道如何做到這一點嗎?

更新:看來上面的第三種方法是這樣做的方式。剃刀顯然是這樣的:

@{using(Html.BeginForm<Controller>(c => c.Method())) // Interpreted as c# 
    {            // interpreted as c# 
     <p>           // interpreted as HTML 
     Some text         // interpreted as HTML 
     @Code          // interpreted as c# 
     </p>           // interpreted as HTML 
    }            // interpreted as c# 
}             // interpreted as c# 

不是最明顯的做事方式,但它的作品。

更新2:剃刀可能已經在某些時候更新,因爲現在上面的選項#1按預期工作。

@using(Html.BeginForm<Controller>(c => c.Method())) 
{ 
    Some code 
} 
+0

它似乎對我的工作很好。但是沒有'BeginForm '可用(我做了一個快速輔助方法來測試),所以你使用的是外部庫還是其他的東西? Razor語法中的錯誤是什麼? – Buildstarted

+0

我們使用Microsoft.Web.Mvc.dll中的MvcContrib擴展,其中包含許多強類型的html助手。錯誤是@(Html.BeginForm (...))工作正常,但@using(Html.BeginForm (...))沒有,我不能找出一種方法來格式化它,以便它工作。 –

回答

7

,如果你換用括號括住整個聲明內容:

@(using(Html.BeginForm<Controller>(c => c.Method()))) 

或者使用一個代碼塊?

HTH。

+0

我試過了,它不好。上面添加了不同嘗試的示例。 –

+0

適用於MVC 4.5中的我。 –