2017-10-09 67 views
1

我正在爲ASP.NET MVC使用kendo UI。我想知道是否有方法使用Razor將條件邏輯添加到DropDownList的HtmlAttributes中。正如你可以從我的例子看到使用條件邏輯將客戶端驗證「需要」到來自ASP.NET MVC UI的Kendo DropDownList Api

@(Html.Kendo().DatePickerFor(model => model.RequestedDate) 
    .Name("RequestedDate") 
    .Format("dd/MM/yyyy") 
    .HtmlAttributes(new { style = "width:100%" }) 
    .Value(Model.DocumentId != null ? Model.RequestedDate : DateTime.Today) 
) 

我設置的價值根據如果我的模型有Id或不。我想知道我的問題是否有語法。也許類似的東西

@(Html.Kendo().DatePickerFor(model => model.RequestedDate) 
    .Name("RequestedDate") 
    .Format("dd/MM/yyyy") 
    .HtmlAttributes(new { style = "width:100%" if(Model.DocumentId){ required = "required" }) 
    .Value(Model.DocumentId != null ? Model.RequestedDate : DateTime.Today) 
) 

我知道它可以通過JavaScript來實現對數據綁定事件可能的元素,但我的問題是,如果在我的剃鬚刀頁這樣做的方式。

回答

1

我upvoted @ChrisC回答是因爲他幫助我以我需要的方式看待它。我處理它的方式如下:

@(Html.Kendo().DatePickerFor(model => model.RequestedDate) 
    .Name("RequestedDate").Format("dd/MM/yyyy") 
    .HtmlAttributes(Model.DocumentId == null ? (object) new { style = "width:100%" } : new { style = "width:100%", required = "required" }) 
    .Value(Model.DocumentId != null ? Model.RequestedDate : DateTime.Today) 
) 
1

Razor本質上只是在視圖中運行的C#。你在這裏要做的是在對象的範圍內包裝一個if聲明,即它不會被編譯。

你能做的最好的事情是從HtmlAttributes方法並拆分移動的對象值與if語句來代替:

@{ 
object myAttributes = null; 

    if(Model.DocumentId) { 
     myAttributes = new { style = "width:100%", required = "required" } 
    } 
    else { 
     myAttributes = new { style = "width:100%" } 
    } 
} 

,然後有

@(Html.Kendo().DatePickerFor(model => model.RequestedDate) 
    .Name("RequestedDate") 
    .Format("dd/MM/yyyy") 
    .HtmlAttributes(myAttributes) 
    .Value(Model.DocumentId != null ? Model.RequestedDate : DateTime.Today) 
)