私はクラスの複数のプロパティを公開MVC HTMLヘルパーを構築しています。式ラムダ
これが私のクラスである:
public class Foo {
public string Section { get; set; }
public string Value { get; set; }
}
そして、ここでは私のヘルパーです:
public partial class FooBuilder<TModel> {
public MvcHtmlString DropDownFooListFor(Expression<Func<TModel, Foo>> expression, string optionLabel = null, IDictionary<string, object> htmlAttributes = null) {
var metadata = ModelMetadata.FromLambdaExpression(expression, Helper.ViewData);
var model = metadata.Model as Foo;
var items = FooUtility.GetFooValues(metadata.PropertyName).Select(x => new SelectListItem {
Text = x,
Value = x,
Selected = model != null && model.Value == x
});
var value = Expression.Lambda<Func<TModel, string>>(Expression.MakeMemberAccess(expression.Body, typeof(Foo).GetProperty("Value")), Expression.Parameter(typeof(TModel), "value"));
var list = Expression.Lambda<Func<TModel, string>>(Expression.MakeMemberAccess(expression.Body, typeof(Foo).GetProperty("Section")), Expression.Parameter(typeof(TModel), "section"));
//Helper.ViewContext.Writer.Write(
// Helper.HiddenFor(list, new { value = string.Format("{0}#{1}", FooUtility.GetCurrentSection(), metadata.PropertyName) })
//);
return Helper.DropDownListFor(value, items, optionLabel, htmlAttributes);
}
}
その後、私のビュー内、私は
@(Html.Foo().DropDownFooListFor(x => x.Bar))
ヘルパーを呼び出し、ここで私のですビューモデル:
public class Baz {
public Foo Bar { get; set; }
}
私の問題は、3行のコメントアウトを解除すると(つまり:list
という表現を使用すると)、それは悲惨に失敗します。予想通りvalue
作品を使用したが、list
を使用して、なぜ私は得ることはありません
はしていません。
私は、次の例外を取得:タイプの 'X'
変数のスコープから参照 'Namespace.Baz' ''、それは は
Baz
は私で、再び
が定義されていません。ビューモデル。
私は間違っていますか?
編集:OK、これは私が思ったことを悪いです。私はDropDownListFor
と私の式のいずれかを使用する場合、それは動作しますが、それはHiddenFor
、またはTextBoxFor
としません。
編集2:ここではHelper
が定義されている方法です。
public partial class FooBuilder<TModel> {
public HtmlHelper<TModel> Helper { get; set; }
}
public static class FooHelpers {
public static FooBuilder<TModel> Foo<TModel>(this HtmlHelper<TModel> helper) {
return new FooBuilder<TModel> { Helper = helper };
}
}
可能な複製:http://stackoverflow.com/questions/6106283/memberexpression-invalidoperationexpression-variable-x-referenced-from-scope –
@NickLarsenどこで同じ名前の異なるパラメータを作成していますか?好奇心のうち –
は、コメントアウトコードが出力に直接隠さを書いて、なぜあなたはそれをやっていますか?また、 'Helper'がどこに定義されているかを示すために、このコードを更新できますか? –