0
我創建了一個自定義TextBoxFor
方法,以便在我的ViewModel上使用自定義的「InputField」類來簡化在剃鬚刀中的開發。獲取表達式的自定義對象<model,property>
視圖模型
public enum FieldState
{
NORMAL,
DISABLED
}
public class InputField
{
public FieldState State
{
get;
internal set;
}
public string Value
{
get;
private set;
}
public InputField()
{
State = FieldState.NORMAL;
Value = string.Empty;
}
public override string ToString()
{
return Value;
}
public static implicit operator string(InputField field_)
{
return field_.Value ?? string.Empty;
}
}
public class PrintJobForm
{
public InputField Material
{
get;
set;
}
}
擴展
public static MvcHtmlString ClassedTextBoxFor<TModel, TProperty>(
this HtmlHelper<TModel> html_,
Expression<Func<TModel, TProperty>> expr_,
string classes_ = "")
where TProperty : InputField
{
classes_ += " form-control";
if (expr_.Compile().Invoke().State == FieldState.DISABLED) {
classes_ += " disabled";
}
return html_.TextBoxFor(expr_, new {
@class = classes_
});
}
Form.cshtml
<div class="control-group">
<div class="col-md-3">
@Html.ClassedTextBoxFor(model_ => model_.Material)
@Html.ValidationMessageFor(model_ => model_.Material)
</div>
</div>
我想我想做的事很簡單。目前的問題是此行
if (expr_.Compile().Invoke().State == FieldState.DISABLED) {
classes_ += " disabled";
}
的Invoke()
要求TModel
類型的參數。我怎樣才能從表達式中獲得這個,所以我可以在HTML中正確設置「禁用」狀態?