2011-08-12 17 views
1

我有一個看起來像這樣條件邏輯來包裝一些HTML中Html.BeginForm

@using(Html.BeginForm(MVC.Account.Info())) 
{ 
    <p>blah blah blah</p> 

    <input type="submit" value="Submit!" /> 
} 

剃刀視圖現在我只想渲染表單並提交如果User.Identity.IsAuthenticated

如果縮進水平分別顯著,可能看起來像這樣

@if(User.Identity.IsAuthenticated) // wraps the using and its open brace 
{ 
    @using(Html.BeginForm(MVC.Account.Info())) 
    { 
} 

     <p>blah blah blah</p> 

@if(User.Identity.IsAuthenticated) // wraps the input and the using closing brace 
{ 
     <input type="submit" value="Submit!" /> 
    } 
} 

但是,當然,這種語法不起作用。有人知道一個很好的方法來做到這一點?

回答

5

最終使用剃刀助手。我覺得這是最好的辦法,還是不會介意看到的替代品,如果你有一個很好的

@helper Info() 
{ 
    <p>blah blah blah</p> 
} 

@if(User.Identity.IsAuthenticated) 
{ 
    using(Html.BeginForm(MVC.Account.Info())) 
    { 
     @Info() 
     <input type="submit" value="Submit!" /> 
    } 
} 
else 
{ 
    @Info() 
} 
1
@if(User.Identity.IsAuthenticated) 
{ 
    @using(Html.BeginForm(MVC.Account.Info())) 
    { 
     <p>blah blah blah</p> 
     <input type="submit" value="Submit!" /> 
    } 
} 
else 
{ 
    <p>blah blah blah</p> 
} 

如果你真的不想重複自己,你可以使用JavaScript來移動<p>形式裏面,如果它的存在。

0

您可以刪除using如果你自己處置的成員。

@{ 
    MvcForm htmlForm = null; 
    if (User.Identity.IsAuthenticated) 
    { 
     //render the begin of a <form> tag 
     htmlForm = Html.BeginForm(MVC.Account.Info()); 
    } 
} 

@* content goes here *@ 
<p>blah blah blah</p> 

@if (htmlForm != null) 
{ 
    //render the end of </form> 
    <input type="submit" value="Submit!" /> 
    htmlForm.EndForm(); 
}