使用条件逻辑将客户端验证“需要”到来自ASP.NET MVC UI的Kendo DropDownList Api
问题描述:
我正在为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来实现对数据绑定事件可能的元素,但我的问题是,如果在我的剃须刀页这样做的方式。
答
我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)
)
答
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)
)